blob: ff6117c163f519ec68cae1aceb8fdb99f0704f85 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
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;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090020import 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;
Chalard Jean9a396cc2018-02-21 18:43:54 +090024import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090025import 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;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090033import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000035import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070036import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080037import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
38import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
39import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090040import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090041import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090042import static android.net.ConnectivityManager.TYPE_MOBILE;
43import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
44import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
45import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
46import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
47import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
48import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
49import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
50import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
51import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070052import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090053import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070054import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090055import static android.net.ConnectivityManager.TYPE_WIFI;
56import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070057import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070058import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080059import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080060import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080061import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070062import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040064import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090065import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090066import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090067import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
70import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060071import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080075import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
76import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080077import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080079import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
80import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080081import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
82import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
83import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090084import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090085import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060086import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070087import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080088import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090089import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070090import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
91import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070092import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080093import static android.os.Process.VPN_UID;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090094import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Patrick Rohr2857ac42022-01-21 14:58:16 +010095import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070096import static android.system.OsConstants.IPPROTO_TCP;
97import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060098
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090099import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
Xiao Ma60142372022-07-16 17:30:20 +0900100import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
paulhu3ffffe72021-09-16 10:15:22 +0800101import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
102import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
103import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900104
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800105import static java.util.Map.Entry;
106
Chalard Jean5b639762020-03-09 21:25:37 +0900107import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000108import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800109import android.annotation.Nullable;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800110import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800111import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800112import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700113import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700114import android.app.admin.DevicePolicyManager;
junyulaie7c7d2a2021-01-26 15:29:15 +0800115import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700116import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800117import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800118import android.content.ContentResolver;
119import android.content.Context;
120import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700121import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800122import android.content.pm.PackageManager;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700123import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900124import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900125import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700126import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800127import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800128import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800129import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900130import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800131import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900132import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900133import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800134import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900135import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800136import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700137import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900138import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800139import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800140import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800141import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800142import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800143import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900144import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900145import android.net.INetworkMonitor;
146import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900147import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900148import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700149import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800150import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900151import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900152import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900153import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800154import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100155import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800156import android.net.NativeNetworkConfig;
157import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800158import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700159import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700160import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900161import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700162import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800163import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700164import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900165import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900166import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000167import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900168import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700169import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900170import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700171import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900172import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700173import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800174import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900175import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700176import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000177import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800178import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900179import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800180import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400181import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700182import android.net.QosCallbackException;
183import android.net.QosFilter;
184import android.net.QosSocketFilter;
185import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700186import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800187import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800188import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800189import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900190import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400191import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800192import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800193import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400194import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800195import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900196import android.net.VpnTransportInfo;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900197import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900198import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800199import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900200import android.net.networkstack.ModuleNetworkStackClient;
201import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900202import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800203import android.net.resolv.aidl.DnsHealthEventParcel;
204import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
205import android.net.resolv.aidl.Nat64PrefixEventParcel;
206import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900207import android.net.shared.PrivateDnsConfig;
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900208import android.net.util.MultinetworkPolicyTracker;
he_won.hwang881307a2022-03-15 21:23:52 +0900209import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800210import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800211import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800212import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700213import android.os.Bundle;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800214import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700215import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700216import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800217import android.os.Looper;
218import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700219import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700220import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900221import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800222import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700223import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700224import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800225import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700226import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900227import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900228import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700229import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700230import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400231import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900233import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700234import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700235import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700236import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800237import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900238import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000239import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600240import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900241import android.util.Pair;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700242import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700243import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800244
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900245import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400246import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400247import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700248import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900249import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800250import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900251import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800252import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900253import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900254import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100255import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900256import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
257import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900258import com.android.net.module.util.LocationPermissionChecker;
lifrade6c2a2021-03-04 14:08:08 +0800259import com.android.net.module.util.NetworkCapabilitiesUtils;
Junyu Lai00d92df2022-07-05 11:01:52 +0800260import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800261import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100262import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000263import com.android.net.module.util.netlink.InetDiagMessage;
Chalard Jean7284daa2019-05-30 14:58:29 +0900264import com.android.server.connectivity.AutodestructReference;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800265import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800266import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900267import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900268import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500269import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700270import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900271import com.android.server.connectivity.FullScore;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900272import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100273import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700274import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700275import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600276import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900277import com.android.server.connectivity.NetworkNotificationManager;
278import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900279import com.android.server.connectivity.NetworkOffer;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900280import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700281import com.android.server.connectivity.PermissionMonitor;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800282import com.android.server.connectivity.ProfileNetworkPreferenceList;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900283import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700284import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800285import com.android.server.connectivity.UidRangeUtils;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600286
Josh Gao461a1222020-06-16 15:58:11 -0700287import libcore.io.IoUtils;
288
The Android Open Source Project28527d22009-03-03 19:31:44 -0800289import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100290import java.io.IOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800291import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900292import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700293import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700294import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900295import java.net.InetSocketAddress;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700296import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700297import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700298import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700299import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800300import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900301import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800302import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700303import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700304import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700305import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700306import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900307import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700308import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900309import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600310import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900311import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600312import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900313import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800314
315/**
316 * @hide
317 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800318public class ConnectivityService extends IConnectivityManager.Stub
319 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900320 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800321
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900322 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900323 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900324 private static final String NETWORK_ARG = "networks";
325 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800326 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900327
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900328 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900329 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
330 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800331
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900332 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700333
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100334 /**
335 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
336 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800337 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100338 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
339 * (preferably via runtime resource overlays).
340 */
341 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
342 "http://connectivitycheck.gstatic.com/generate_204";
343
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700344 // TODO: create better separation between radio types and network types
345
Robert Greenwalt2034b912009-08-12 16:08:25 -0700346 // how long to wait before switching back to a radio's default network
347 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
348 // system property that can override the above value
349 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
350 "android.telephony.apn-restore";
351
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900352 // How long to wait before putting up a "This network doesn't have an Internet connection,
353 // connect anyway?" dialog after the user selects a network that doesn't validate.
354 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
355
Chalard Jean5fb43c72022-09-08 19:03:14 +0900356 // How long to wait before considering that a network is bad in the absence of any form
357 // of connectivity (valid, partial, captive portal). If none has been detected after this
358 // delay, the stack considers this network bad, which may affect how it's handled in ranking
359 // according to config_networkAvoidBadWifi.
360 private static final int INITIAL_EVALUATION_TIMEOUT_MS = 20 * 1000;
361
junyulai0ac374f2020-12-14 18:41:52 +0800362 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900363 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
364 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800365 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700366
he_won.hwang881307a2022-03-15 21:23:52 +0900367 // The maximum value for the blocking validation result, in milliseconds.
368 public static final int MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS = 10000;
369
Daniel Brightf9e945b2020-06-15 16:10:01 -0700370 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900371 @VisibleForTesting
372 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700373
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900374 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700375 @VisibleForTesting
376 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900377
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900378 @VisibleForTesting
379 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800380 @VisibleForTesting
381 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900382 // True if the cell radio of the device is capable of time-sharing.
383 @VisibleForTesting
384 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900385
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800386 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800387 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800388 private final int mReleasePendingIntentDelayMs;
389
Chalard Jean46bfbf02022-02-02 00:56:25 +0900390 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900391
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000392 @VisibleForTesting
393 protected final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700394
Chalard Jean9473c982021-07-29 20:03:04 +0900395 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800396 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700397 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800398 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700399
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900400 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700401
junyulaif2c67e42018-08-07 19:50:45 +0800402 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000403 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
404 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800405 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900406 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800407
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900408 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900409 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000410 // The Context is created for UserHandle.ALL.
411 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900412 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900413 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700414 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700415 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800416
Chenbo Feng15416292018-11-08 17:36:21 -0800417 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800418 protected IDnsResolver mDnsResolver;
419 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800420 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700421 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900422 private final NetworkStatsManager mStatsManager;
423 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800424 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700425
Benedict Wong493e04b2018-11-09 14:45:34 -0800426 /**
427 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
428 * instances.
429 */
430 @GuardedBy("mTNSLock")
431 private TestNetworkService mTNS;
432
433 private final Object mTNSLock = new Object();
434
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700435 private String mCurrentTcpBufferSizes;
436
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900437 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
lifraf3a3492021-03-10 13:58:14 +0800438 new Class[] { ConnectivityService.class, NetworkAgent.class, NetworkAgentInfo.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900439
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500440 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400441 // Tear down networks that have no chance (e.g. even if validated) of becoming
442 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500443 // all networks have been rematched against all NetworkRequests.
444 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400445 // Don't reap networks. This should be passed when some networks have not yet been
446 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500447 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900448 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500449
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900450 private enum UnneededFor {
451 LINGER, // Determine whether this network is unneeded and should be lingered.
452 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
453 }
454
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700455 /**
paulhuaa0743d2021-05-26 21:56:03 +0800456 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800457 * should have priority. The order is passed to netd which will use it together
458 * with UID ranges to generate the corresponding IP rule. This serves to
459 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800460 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800461 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000462 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800463 *
paulhu48291862021-07-14 14:53:57 +0800464 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
465 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800466 */
paulhu48291862021-07-14 14:53:57 +0800467 // Used when sending to netd to code for "no order".
468 static final int PREFERENCE_ORDER_NONE = 0;
469 // Order for requests that don't code for a per-app preference. As it is
470 // out of the valid range, the corresponding order should be
471 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800472 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800473 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800474 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800475 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
476 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800477 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800478 static final int PREFERENCE_ORDER_OEM = 10;
479 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800480 // See {@link #setProfileNetworkPreference}.
481 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800482 static final int PREFERENCE_ORDER_PROFILE = 20;
483 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800484 // better scores are connected.
485 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800486 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800487 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900488 // Preference order that signifies the network shouldn't be set as a default network for
489 // the UIDs, only give them access to it. TODO : replace this with a boolean
490 // in NativeUidRangeConfig
491 @VisibleForTesting
492 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
493 // Bound for the lowest valid preference order.
494 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800495
496 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700497 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700498 * from one net to another. Clear happens when we get a new
499 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
500 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700501 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700502 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700503
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700504 /**
505 * used internally to reload global proxy settings
506 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700507 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700508
Robert Greenwalt34848c02011-03-25 13:09:25 -0700509 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400510 * PAC manager has received new port.
511 */
512 private static final int EVENT_PROXY_HAS_CHANGED = 16;
513
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700514 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900515 * used internally when registering NetworkProviders
516 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700517 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900518 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700519
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700520 /**
521 * used internally when registering NetworkAgents
522 * obj = Messenger
523 */
524 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
525
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700526 /**
527 * used to add a network request
528 * includes a NetworkRequestInfo
529 */
530 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
531
532 /**
533 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900534 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700535 * cancel it.
536 * includes a NetworkRequestInfo
537 */
538 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
539
540 /**
541 * used to add a network listener - no request
542 * includes a NetworkRequestInfo
543 */
544 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
545
546 /**
547 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400548 * arg1 = UID of caller
549 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700550 */
551 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
552
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700553 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900554 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700555 * obj = Messenger
556 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900557 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700558
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700559 /**
560 * used internally to expire a wakelock when transitioning
561 * from one net to another. Expire happens when we fail to find
562 * a new network (typically after 1 minute) -
563 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
564 * a replacement network.
565 */
566 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
567
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700568 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800569 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400570 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800571 */
572 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
573
574 /**
575 * used to remove a pending intent and its associated network request.
576 * arg1 = UID of caller
577 * obj = PendingIntent
578 */
579 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
580
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900581 /**
582 * used to specify whether a network should be used even if unvalidated.
583 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
584 * arg2 = whether to remember this choice in the future (1 or 0)
585 * obj = network
586 */
587 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
588
589 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700590 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900591 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700592 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900593
Paul Jensenc8873fc2015-06-17 14:15:39 -0400594 /**
595 * used to add a network listener with a pending intent
596 * obj = NetworkRequestInfo
597 */
598 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
599
Hugo Benichid6b510a2017-04-06 17:22:18 +0900600 /**
601 * used to specify whether a network should not be penalized when it becomes unvalidated.
602 */
603 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
604
605 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700606 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900607 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700608 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900609
Erik Kline31b4a9e2018-01-11 21:07:29 +0900610 // Handle changes in Private DNS settings.
611 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
612
dalyk1720e542018-03-05 12:42:22 -0500613 // Handle private DNS validation status updates.
614 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
615
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900616 /**
617 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
618 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800619 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
620 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
621 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900622 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900623 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900624
625 /**
626 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
627 * config was resolved.
628 * obj = PrivateDnsConfig
629 * arg2 = netid
630 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900631 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900632
633 /**
634 * Request ConnectivityService display provisioning notification.
635 * arg1 = Whether to make the notification visible.
636 * arg2 = NetID.
637 * obj = Intent to be launched when notification selected by user, null if !arg1.
638 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900639 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900640
641 /**
lucaslin2240ef62019-03-12 13:08:03 +0800642 * Used to specify whether a network should be used even if connectivity is partial.
643 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
644 * false)
645 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
646 * obj = network
647 */
lucaslin444d43a2020-02-20 16:56:59 +0800648 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800649
650 /**
lucasline117e2e2019-10-22 18:27:33 +0800651 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
652 * Both of the arguments are bitmasks, and the value of bits come from
653 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900654 * arg1 = unused
655 * arg2 = netId
656 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800657 */
lucaslin444d43a2020-02-20 16:56:59 +0800658 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800659
660 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900661 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
662 * arg1 = unused
663 * arg2 = netId
664 * obj = captive portal data
665 */
lucaslin444d43a2020-02-20 16:56:59 +0800666 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900667
668 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900669 * Used by setRequireVpnForUids.
670 * arg1 = whether the specified UID ranges are required to use a VPN.
671 * obj = Array of UidRange objects.
672 */
673 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
674
675 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900676 * Used internally when setting the default networks for OemNetworkPreferences.
677 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800678 */
679 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
680
681 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800682 * Used to indicate the system default network becomes active.
683 */
684 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
685
686 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900687 * Used internally when setting a network preference for a user profile.
688 * obj = Pair<ProfileNetworkPreference, Listener>
689 */
690 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
691
692 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000693 * Event to specify that reasons for why an uid is blocked changed.
694 * arg1 = uid
695 * arg2 = blockedReasons
696 */
697 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
698
699 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900700 * Event to register a new network offer
701 * obj = NetworkOffer
702 */
703 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
704
705 /**
706 * Event to unregister an existing network offer
707 * obj = INetworkOfferCallback
708 */
709 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
710
711 /**
paulhu51f77dc2021-06-07 02:34:20 +0000712 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
713 */
714 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
715
716 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800717 * Event to set temporary allow bad wifi within a limited time to override
718 * {@code config_networkAvoidBadWifi}.
719 */
720 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
721
722 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100723 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
724 */
725 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
726
727 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900728 * The initial evaluation period is over for this network.
729 *
730 * If no form of connectivity has been found on this network (valid, partial, captive portal)
731 * then the stack will now consider it to have been determined bad.
732 */
733 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
734
735 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900736 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
737 * should be shown.
738 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900739 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900740
741 /**
742 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
743 * should be hidden.
744 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900745 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900746
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800747 /**
748 * The maximum alive time to allow bad wifi configuration for testing.
749 */
750 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
751
Patrick Rohr2857ac42022-01-21 14:58:16 +0100752 /**
753 * The priority of the tc police rate limiter -- smaller value is higher priority.
754 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
755 */
756 private static final short TC_PRIO_POLICE = 1;
757
758 /**
759 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
760 */
761 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700762 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100763
Hugo Benichi47011212017-03-30 10:46:05 +0900764 private static String eventName(int what) {
765 return sMagicDecoderRing.get(what, Integer.toString(what));
766 }
767
paulhua10d8212020-11-10 15:32:56 +0800768 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900769 final DnsResolverServiceManager dsm = context.getSystemService(
770 DnsResolverServiceManager.class);
771 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800772 }
773
Cody Kesting73708bf2019-12-18 10:57:50 -0800774 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900775 @VisibleForTesting
776 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700777 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700778 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700779 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700780 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800781 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
782 @VisibleForTesting
783 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
784
Erik Kline32120082017-12-13 19:40:49 +0900785 private final DnsManager mDnsManager;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900786 private final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700787
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400788 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800789 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400790
Chalard Jean46bfbf02022-02-02 00:56:25 +0900791 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800792 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700793
Chalard Jean5d70ba42018-06-07 16:44:04 +0900794 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
795 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000796 @VisibleForTesting
797 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400798
Erik Kline05f2b402015-04-30 12:58:40 +0900799 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700800
Chalard Jean46bfbf02022-02-02 00:56:25 +0900801 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400802
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700803 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900804 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700805
Valentin Iftime9fa35092019-09-24 13:32:13 +0200806 private Set<String> mWolSupportedInterfaces;
807
Roshan Pius08c94fb2020-01-16 12:17:17 -0800808 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800809 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800810 private final AppOpsManager mAppOpsManager;
811
812 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400813
Chalard Jean46bfbf02022-02-02 00:56:25 +0900814 private final KeepaliveTracker mKeepaliveTracker;
815 private final QosCallbackTracker mQosCallbackTracker;
816 private final NetworkNotificationManager mNotifier;
817 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900818
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700819 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800820 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700821
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900822 // Sequence number for NetworkProvider IDs.
823 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
824 NetworkProvider.FIRST_PROVIDER_ID);
825
Erik Klineedf878b2015-07-09 18:24:03 +0900826 // NetworkRequest activity String log entries.
827 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
828 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
829
Hugo Benichid159fdd2016-07-11 11:05:12 +0900830 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900831 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900832 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
833
Hugo Benichi47011212017-03-30 10:46:05 +0900834 private static final int MAX_WAKELOCK_LOGS = 20;
835 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900836 private int mTotalWakelockAcquisitions = 0;
837 private int mTotalWakelockReleases = 0;
838 private long mTotalWakelockDurationMs = 0;
839 private long mMaxWakelockDurationMs = 0;
840 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900841
Hugo Benichi208c0102016-07-28 17:53:06 +0900842 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900843
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700844 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900845 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700846
Erik Kline95ecfee2016-10-02 18:02:14 +0900847 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900848 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900849
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900850 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800851 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
852 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800853
Patrick Rohr2857ac42022-01-21 14:58:16 +0100854 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
855 // configured via {@link
856 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
857 // Only the handler thread is allowed to access this field.
858 private long mIngressRateLimit = -1;
859
Robert Greenwalt802c1102014-06-02 15:32:02 -0700860 /**
861 * Implements support for the legacy "one network per network type" model.
862 *
863 * We used to have a static array of NetworkStateTrackers, one for each
864 * network type, but that doesn't work any more now that we can have,
865 * for example, more that one wifi network. This class stores all the
866 * NetworkAgentInfo objects that support a given type, but the legacy
867 * API will only see the first one.
868 *
869 * It serves two main purposes:
870 *
871 * 1. Provide information about "the network for a given type" (since this
872 * API only supports one).
873 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
874 * the first network for a given type changes, or if the default network
875 * changes.
876 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900877 @VisibleForTesting
878 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900879
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900880 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900881 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900882
Robert Greenwalt802c1102014-06-02 15:32:02 -0700883 /**
884 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
885 * Each list holds references to all NetworkAgentInfos that are used to
886 * satisfy requests for that network type.
887 *
888 * This array is built out at startup such that an unsupported network
889 * doesn't get an ArrayList instance, making this a tristate:
890 * unsupported, supported but not active and active.
891 *
892 * The actual lists are populated when we scan the network types that
893 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900894 *
895 * Threading model:
896 * - addSupportedType() is only called in the constructor
897 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
898 * They are therefore not thread-safe with respect to each other.
899 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
900 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900901 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900902 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700903 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900904 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900905 @NonNull
906 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700907
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900908 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
909 // an entry have no timer (equivalent to -1). Lazily loaded.
910 @NonNull
911 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
912
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900913 LegacyTypeTracker(@NonNull ConnectivityService service) {
914 mService = service;
915 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700916 }
917
Chiachang Wang3bc52762021-11-25 14:17:57 +0800918 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
919 // addressed.
920 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900921 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
922 final PackageManager pm = ctx.getPackageManager();
923 if (pm.hasSystemFeature(FEATURE_WIFI)) {
924 addSupportedType(TYPE_WIFI);
925 }
926 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
927 addSupportedType(TYPE_WIFI_P2P);
928 }
929 if (tm.isDataCapable()) {
930 // Telephony does not have granular support for these types: they are either all
931 // supported, or none is supported
932 addSupportedType(TYPE_MOBILE);
933 addSupportedType(TYPE_MOBILE_MMS);
934 addSupportedType(TYPE_MOBILE_SUPL);
935 addSupportedType(TYPE_MOBILE_DUN);
936 addSupportedType(TYPE_MOBILE_HIPRI);
937 addSupportedType(TYPE_MOBILE_FOTA);
938 addSupportedType(TYPE_MOBILE_IMS);
939 addSupportedType(TYPE_MOBILE_CBS);
940 addSupportedType(TYPE_MOBILE_IA);
941 addSupportedType(TYPE_MOBILE_EMERGENCY);
942 }
943 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
944 addSupportedType(TYPE_BLUETOOTH);
945 }
946 if (pm.hasSystemFeature(FEATURE_WATCH)) {
947 // TYPE_PROXY is only used on Wear
948 addSupportedType(TYPE_PROXY);
949 }
950 // Ethernet is often not specified in the configs, although many devices can use it via
951 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +0000952 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900953 addSupportedType(TYPE_ETHERNET);
954 }
955
956 // Always add TYPE_VPN as a supported type
957 addSupportedType(TYPE_VPN);
958 }
959
960 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -0700961 if (mTypeLists[type] != null) {
962 throw new IllegalStateException(
963 "legacy list for type " + type + "already initialized");
964 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900965 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -0700966 }
967
Robert Greenwalt802c1102014-06-02 15:32:02 -0700968 public boolean isTypeSupported(int type) {
969 return isNetworkTypeValid(type) && mTypeLists[type] != null;
970 }
971
972 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +0900973 synchronized (mTypeLists) {
974 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
975 return mTypeLists[type].get(0);
976 }
Robert Greenwalt802c1102014-06-02 15:32:02 -0700977 }
Hugo Benichi389633f2016-06-21 09:48:07 +0900978 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700979 }
980
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900981 public int getRestoreTimerForType(int type) {
982 synchronized (mTypeLists) {
983 if (mRestoreTimers == null) {
984 mRestoreTimers = loadRestoreTimers();
985 }
986 return mRestoreTimers.getOrDefault(type, -1);
987 }
988 }
989
990 private ArrayMap<Integer, Integer> loadRestoreTimers() {
991 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900992 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900993 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
994 for (final String config : configs) {
995 final String[] splits = TextUtils.split(config, ",");
996 if (splits.length != 2) {
997 logwtf("Invalid restore timer token count: " + config);
998 continue;
999 }
1000 try {
1001 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1002 } catch (NumberFormatException e) {
1003 logwtf("Invalid restore timer number format: " + config, e);
1004 }
1005 }
1006 return ret;
1007 }
1008
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001009 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001010 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001011 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001012 log("Sending " + state
1013 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001014 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001015 }
1016 }
1017
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001018 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1019 // network type, to preserve previous behaviour.
1020 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1021 if (vpnNai != mService.getLegacyLockdownNai()) return;
1022
1023 if (vpnNai.declaredUnderlyingNetworks == null
1024 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1025 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1026 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1027 return;
1028 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001029 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001030 vpnNai.declaredUnderlyingNetworks[0]);
1031 if (underlyingNai == null) return;
1032
1033 final int type = underlyingNai.networkInfo.getType();
1034 final DetailedState state = DetailedState.CONNECTED;
1035 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1036 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1037 }
1038
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001039 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001040 public void add(int type, NetworkAgentInfo nai) {
1041 if (!isTypeSupported(type)) {
1042 return; // Invalid network type.
1043 }
1044 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1045
1046 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1047 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001048 return;
1049 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001050 synchronized (mTypeLists) {
1051 list.add(nai);
1052 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001053
Chalard Jean5b409c72021-02-04 13:12:59 +09001054 // Send a broadcast if this is the first network of its type or if it's the default.
1055 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001056
1057 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1058 // to preserve previous behaviour.
1059 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001060 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001061 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1062 mService.sendLegacyNetworkBroadcast(nai, state, type);
1063 }
1064
1065 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1066 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001067 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001068 }
1069
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001070 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001071 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001072 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1073 if (list == null || list.isEmpty()) {
1074 return;
1075 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001076 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001077
Hugo Benichi389633f2016-06-21 09:48:07 +09001078 synchronized (mTypeLists) {
1079 if (!list.remove(nai)) {
1080 return;
1081 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001082 }
1083
Lorenzo Colitti49767722015-05-01 00:30:10 +09001084 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001085 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1086 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001087 }
1088
1089 if (!list.isEmpty() && wasFirstNetwork) {
1090 if (DBG) log("Other network available for type " + type +
1091 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001092 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001093 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001094 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001095 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001096 }
1097 }
1098
1099 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001100 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1101 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001102 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001103 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001104 }
1105 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001106
Chalard Jean46bfbf02022-02-02 00:56:25 +09001107 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001108 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001109 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001110 final DetailedState state = nai.networkInfo.getDetailedState();
1111 for (int type = 0; type < mTypeLists.length; type++) {
1112 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001113 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001114 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001115 if (isFirst || contains && isDefault) {
1116 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001117 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001118 }
1119 }
1120 }
1121
Robert Greenwalt94e22142014-07-30 16:31:24 -07001122 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001123 pw.println("mLegacyTypeTracker:");
1124 pw.increaseIndent();
1125 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001126 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001127 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001128 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001129 pw.println();
1130 pw.println("Current state:");
1131 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001132 synchronized (mTypeLists) {
1133 for (int type = 0; type < mTypeLists.length; type++) {
1134 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1135 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001136 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001137 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001138 }
1139 }
1140 pw.decreaseIndent();
1141 pw.decreaseIndent();
1142 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001143 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001144 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001145 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001146
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001147 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001148 /**
1149 * Helper class which parses out priority arguments and dumps sections according to their
1150 * priority. If priority arguments are omitted, function calls the legacy dump command.
1151 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001152 private class LocalPriorityDump {
1153 private static final String PRIORITY_ARG = "--dump-priority";
1154 private static final String PRIORITY_ARG_HIGH = "HIGH";
1155 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1156
1157 LocalPriorityDump() {}
1158
1159 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1160 doDump(fd, pw, new String[] {DIAG_ARG});
1161 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001162 }
1163
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001164 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1165 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001166 }
1167
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001168 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1169 if (args == null) {
1170 dumpNormal(fd, pw, args);
1171 return;
1172 }
1173
1174 String priority = null;
1175 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1176 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1177 argIndex++;
1178 priority = args[argIndex];
1179 }
1180 }
1181
1182 if (PRIORITY_ARG_HIGH.equals(priority)) {
1183 dumpHigh(fd, pw);
1184 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1185 dumpNormal(fd, pw, args);
1186 } else {
1187 // ConnectivityService publishes binder service using publishBinderService() with
1188 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001189 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1190 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001191 // TODO: Integrate into signal dump.
1192 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001193 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001194 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001195 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001196
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001197 /**
1198 * Dependencies of ConnectivityService, for injection in tests.
1199 */
1200 @VisibleForTesting
1201 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001202 public int getCallingUid() {
1203 return Binder.getCallingUid();
1204 }
1205
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001206 /**
1207 * Get system properties to use in ConnectivityService.
1208 */
1209 public MockableSystemProperties getSystemProperties() {
1210 return new MockableSystemProperties();
1211 }
1212
1213 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001214 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1215 */
1216 public ConnectivityResources getResources(@NonNull Context ctx) {
1217 return new ConnectivityResources(ctx);
1218 }
1219
1220 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001221 * Create a HandlerThread to use in ConnectivityService.
1222 */
1223 public HandlerThread makeHandlerThread() {
1224 return new HandlerThread("ConnectivityServiceThread");
1225 }
1226
1227 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001228 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001229 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001230 public NetworkStackClientBase getNetworkStack() {
1231 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001232 }
1233
1234 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001235 * @see ProxyTracker
1236 */
1237 public ProxyTracker makeProxyTracker(@NonNull Context context,
1238 @NonNull Handler connServiceHandler) {
1239 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1240 }
1241
1242 /**
1243 * @see NetIdManager
1244 */
1245 public NetIdManager makeNetIdManager() {
1246 return new NetIdManager();
1247 }
1248
1249 /**
1250 * @see NetworkUtils#queryUserAccess(int, int)
1251 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001252 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1253 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001254 }
1255
1256 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001257 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1258 * requires CAP_NET_ADMIN, which the unit tests do not have.
1259 */
1260 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1261 InetSocketAddress remote) {
1262 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1263 }
1264
1265 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001266 * @see MultinetworkPolicyTracker
1267 */
1268 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1269 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1270 return new MultinetworkPolicyTracker(c, h, r);
1271 }
1272
Aaron Huang330a4c02020-10-27 03:36:19 +08001273 /**
1274 * @see BatteryStatsManager
1275 */
1276 public void reportNetworkInterfaceForTransports(Context context, String iface,
1277 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001278 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001279 context.getSystemService(BatteryStatsManager.class);
1280 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1281 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001282
1283 public boolean getCellular464XlatEnabled() {
1284 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1285 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001286
1287 /**
1288 * @see PendingIntent#intentFilterEquals
1289 */
1290 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1291 return a.intentFilterEquals(b);
1292 }
1293
1294 /**
1295 * @see LocationPermissionChecker
1296 */
1297 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1298 return new LocationPermissionChecker(context);
1299 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001300
1301 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001302 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001303 *
1304 * This method returns null in versions before T, where carrier privilege
1305 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001306 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001307 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001308 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1309 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1310 if (SdkLevel.isAtLeastT()) {
1311 return new CarrierPrivilegeAuthenticator(context, tm);
1312 } else {
1313 return null;
1314 }
1315 }
1316
1317 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001318 * @see DeviceConfigUtils#isFeatureEnabled
1319 */
1320 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1321 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1322 TETHERING_MODULE_NAME, defaultEnabled);
1323 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001324
1325 /**
1326 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001327 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001328 * @return BpfNetMaps implementation.
1329 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001330 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1331 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001332 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001333
1334 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001335 * @see ClatCoordinator
1336 */
1337 public ClatCoordinator getClatCoordinator(INetd netd) {
1338 return new ClatCoordinator(
1339 new ClatCoordinator.Dependencies() {
1340 @NonNull
1341 public INetd getNetd() {
1342 return netd;
1343 }
1344 });
1345 }
1346
1347 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001348 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1349 */
1350 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1351 final InterfaceParams params = InterfaceParams.getByName(iface);
1352 if (params == null) {
1353 // the interface might have disappeared.
1354 logw("Failed to get interface params for interface " + iface);
1355 return;
1356 }
1357 try {
1358 // converting rateInBytesPerSecond from long to int is safe here because the
1359 // setting's range is limited to INT_MAX.
1360 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001361 Log.i(TAG,
1362 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001363 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1364 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1365 } catch (IOException e) {
1366 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1367 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1368 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1369 + ") failure: ", e);
1370 }
1371 }
1372
1373 /**
1374 * Wraps {@link TcUtils#tcFilterDelDev}
1375 */
1376 public void disableIngressRateLimit(String iface) {
1377 final InterfaceParams params = InterfaceParams.getByName(iface);
1378 if (params == null) {
1379 // the interface might have disappeared.
1380 logw("Failed to get interface params for interface " + iface);
1381 return;
1382 }
1383 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001384 Log.i(TAG,
1385 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001386 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1387 } catch (IOException e) {
1388 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1389 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1390 }
1391 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001392 }
1393
junyulaie7c7d2a2021-01-26 15:29:15 +08001394 public ConnectivityService(Context context) {
1395 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001396 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1397 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001398 }
1399
1400 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001401 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1402 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001403 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001404
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001405 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001406 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001407 mSystemProperties = mDeps.getSystemProperties();
1408 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001409 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001410 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001411 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1412 // Pass limit - 1 to maintain backward compatibility.
1413 // TODO: Remove the workaround.
1414 mNetworkRequestCounter =
1415 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1416 mSystemNetworkRequestCounter =
1417 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001418
Hugo Benichi208c0102016-07-28 17:53:06 +09001419 mMetricsLog = logger;
Chalard Jean96a4f4b2019-12-10 22:16:53 +09001420 mNetworkRanker = new NetworkRanker();
James Mattis45d81842021-01-10 14:24:24 -08001421 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1422 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001423 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001424 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001425 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001426 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1427 mDefaultNetworkRequests.add(mDefaultRequest);
1428 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001429
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001430 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001431 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001432
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001433 // The default WiFi request is a background request so that apps using WiFi are
1434 // migrated to a better network (typically ethernet) when one comes up, instead
1435 // of staying on WiFi forever.
1436 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1437 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1438
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001439 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1440 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1441 NetworkRequest.Type.BACKGROUND_REQUEST);
1442
Chalard Jean0702f982021-09-16 21:50:07 +09001443 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1444 // TODO: Consider making the timer customizable.
1445 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1446 mCellularRadioTimesharingCapable =
1447 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1448
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001449 mHandlerThread = mDeps.makeHandlerThread();
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001450 mHandlerThread.start();
1451 mHandler = new InternalHandler(mHandlerThread.getLooper());
1452 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001453 mConnectivityDiagnosticsHandler =
1454 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001455
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001456 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001457 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001458
junyulaie7c7d2a2021-01-26 15:29:15 +08001459 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001460 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001461 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001462 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001463
Lorenzo Colittibad9d912019-04-12 10:48:06 +00001464 mNetd = netd;
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001465 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Wink Saville32506bc2013-06-29 21:10:57 -07001466 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001467 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001468 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001469 mCarrierPrivilegeAuthenticator =
1470 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001471
Sudheer Shanka9967d462021-03-18 19:09:25 +00001472 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001473 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1474 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001475 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001476
1477 final PowerManager powerManager = (PowerManager) context.getSystemService(
1478 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001479 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001480 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001481
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001482 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1483 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001484 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001485 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001486 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001487 mProtectedNetworks.add(p);
1488 } else {
1489 if (DBG) loge("Ignoring protectedNetwork " + p);
1490 }
1491 }
1492
soma, kawata29444ae2019-05-23 09:30:40 +09001493 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1494
Wayne Ma2fde98c2022-01-17 18:04:05 +08001495 mPermissionMonitor = new PermissionMonitor(mContext, mNetd, mBpfNetMaps);
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -07001496
James Mattis02220e22021-03-13 19:27:21 -08001497 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001498 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001499 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001500 final IntentFilter userIntentFilter = new IntentFilter();
1501 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1502 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1503 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1504 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001505
James Mattis02220e22021-03-13 19:27:21 -08001506 // Listen to package add/removes for netd
1507 final IntentFilter packageIntentFilter = new IntentFilter();
1508 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1509 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1510 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1511 packageIntentFilter.addDataScheme("package");
1512 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001513 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001514
lucaslind5c2d072021-02-20 18:59:47 +08001515 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001516
Chalard Jean46bfbf02022-02-02 00:56:25 +09001517 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001518 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001519 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001520 } catch (RemoteException | ServiceSpecificException e) {
1521 loge("Error registering event listener :" + e);
1522 }
1523
Erik Kline05f2b402015-04-30 12:58:40 +09001524 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1525 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001526
junyulai7e06ad42019-03-04 22:45:36 +08001527 mKeepaliveTracker = new KeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001528 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001529 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001530
1531 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001532 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001533 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1534 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001535 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001536 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1537 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001538
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001539 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001540 mContext, mHandler, () -> updateAvoidBadWifi());
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001541 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001542
Chiachang Wangc1215d32020-10-20 15:38:58 +08001543 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001544 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001545
Chalard Jean28018572020-12-21 18:36:52 +09001546 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1547 // request that doesn't allow fallback to the default network. It should never be visible
1548 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1549 // arguments like the handler or the DnsResolver.
1550 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001551 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001552 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001553 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001554 new LinkProperties(), new NetworkCapabilities(),
1555 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001556 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1557 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001558
1559 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001560 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1561 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1562 // Even if it could, running on S would at least require mocking out the BPF map,
1563 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1564 // the bpf syscall. http://aosp/1907693
1565 if (SdkLevel.isAtLeastT()) {
1566 mDscpPolicyTracker = new DscpPolicyTracker();
1567 }
Tyler Wear72388212021-09-09 14:49:02 -07001568 } catch (ErrnoException e) {
1569 loge("Unable to create DscpPolicyTracker");
1570 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001571
1572 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1573 mContext);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001574 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001575
Xiao Ma0a171c02022-01-23 16:14:51 +00001576 /**
1577 * Check whether or not the device supports Ethernet transport.
1578 */
1579 public static boolean deviceSupportsEthernet(final Context context) {
1580 final PackageManager pm = context.getPackageManager();
1581 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1582 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1583 }
1584
Chalard Jean46adcf32018-04-18 20:18:38 +09001585 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001586 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1587 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001588 }
1589
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001590 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1591 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001592 final NetworkCapabilities netCap = new NetworkCapabilities();
1593 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001594 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001595 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001596 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001597 return netCap;
1598 }
1599
James Mattis45d81842021-01-10 14:24:24 -08001600 private NetworkRequest createDefaultRequest() {
1601 return createDefaultInternetRequestForTransport(
1602 TYPE_NONE, NetworkRequest.Type.REQUEST);
1603 }
1604
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001605 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001606 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001607 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001608 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001609 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001610 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001611 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001612 netCap.addTransportType(transportType);
1613 }
James Mattis45d81842021-01-10 14:24:24 -08001614 return createNetworkRequest(type, netCap);
1615 }
1616
1617 private NetworkRequest createNetworkRequest(
1618 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001619 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001620 }
1621
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001622 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1623 NetworkRequest.Type type) {
1624 final NetworkCapabilities netCap = new NetworkCapabilities();
1625 netCap.clearAll();
1626 netCap.addCapability(capability);
1627 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1628 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1629 }
1630
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001631 // Used only for testing.
1632 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001633 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001634 // changing ContentResolver to make registerContentObserver non-final).
1635 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1636 // by subclassing SettingsObserver.
1637 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001638 void updateAlwaysOnNetworks() {
1639 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001640 }
1641
Erik Kline9a62f012018-03-21 07:18:33 -07001642 // See FakeSettingsProvider comment above.
1643 @VisibleForTesting
1644 void updatePrivateDnsSettings() {
1645 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1646 }
1647
paulhu51f77dc2021-06-07 02:34:20 +00001648 @VisibleForTesting
1649 void updateMobileDataPreferredUids() {
1650 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1651 }
1652
Patrick Rohr2857ac42022-01-21 14:58:16 +01001653 @VisibleForTesting
1654 void updateIngressRateLimit() {
1655 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1656 }
1657
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001658 private void handleAlwaysOnNetworkRequest(
1659 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001660 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001661 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001662 handleAlwaysOnNetworkRequest(networkRequest, enable);
1663 }
1664
1665 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001666 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001667 if (enable == isEnabled) {
1668 return; // Nothing to do.
1669 }
1670
1671 if (enable) {
1672 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001673 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001674 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001675 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001676 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001677 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1678 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001679 }
1680 }
1681
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001682 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001683 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1684 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1685 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1686 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001687 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1688 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001689 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001690 }
1691
paulhu51f77dc2021-06-07 02:34:20 +00001692 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001693 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001694 private void registerSettingsCallbacks() {
1695 // Watch for global HTTP proxy changes.
1696 mSettingsObserver.observe(
1697 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1698 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1699
Chalard Jean46bfbf02022-02-02 00:56:25 +09001700 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001701 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001702 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001703 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1704
Chalard Jean46bfbf02022-02-02 00:56:25 +09001705 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001706 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001707 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001708 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001709
1710 // Watch for mobile data preferred uids changes.
1711 mSettingsObserver.observe(
1712 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1713 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001714
1715 // Watch for ingress rate limit changes.
1716 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001717 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001718 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1719 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001720 }
1721
Erik Kline31b4a9e2018-01-11 21:07:29 +09001722 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001723 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1724 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001725 }
1726 }
1727
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001728 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001729 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1730 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001731 return mNextNetworkRequestId++;
1732 }
1733
junyulai74f9a8b2018-06-13 15:00:37 +08001734 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001735 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001736 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001737 if (network == null) {
1738 return null;
1739 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001740 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001741 }
1742
1743 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001744 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001745 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001746 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001747 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001748
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001749 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001750 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001751 private NetworkAgentInfo getVpnForUid(int uid) {
1752 synchronized (mNetworkForNetId) {
1753 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1754 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001755 if (nai.isVPN() && nai.everConnected()
1756 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001757 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001758 }
1759 }
1760 }
1761 return null;
1762 }
1763
Chalard Jean46bfbf02022-02-02 00:56:25 +09001764 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001765 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001766 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001767 final NetworkAgentInfo nai = getVpnForUid(uid);
1768 if (nai != null) return nai.declaredUnderlyingNetworks;
1769 return null;
1770 }
1771
Lorenzo Colittia7574052021-01-19 01:33:05 +09001772 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001773 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001774
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001775 final Network[] networks = getVpnUnderlyingNetworks(uid);
1776 if (networks != null) {
1777 // getUnderlyingNetworks() returns:
1778 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1779 // empty array => the VPN explicitly said "no default network".
1780 // non-empty array => the VPN specified one or more default networks; we use the
1781 // first one.
1782 if (networks.length > 0) {
1783 nai = getNetworkAgentInfoForNetwork(networks[0]);
1784 } else {
1785 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001786 }
1787 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001788 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001789 }
1790
1791 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001792 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001793 */
paulhu7aeba372020-12-30 00:42:19 +08001794 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1795 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001796 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001797 if (ignoreBlocked) {
1798 return false;
1799 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001800 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001801 final long ident = Binder.clearCallingIdentity();
1802 try {
1803 final boolean metered = nc == null ? true : nc.isMetered();
1804 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1805 } finally {
1806 Binder.restoreCallingIdentity(ident);
1807 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001808 }
1809
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001810 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001811 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1812 return;
1813 }
Hugo Benichi47011212017-03-30 10:46:05 +09001814 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001815 synchronized (mBlockedAppUids) {
1816 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001817 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001818 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001819 blocked = false;
1820 } else {
1821 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001822 }
1823 }
Hugo Benichi47011212017-03-30 10:46:05 +09001824 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1825 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1826 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001827 }
1828
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001829 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001830 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1831 return;
1832 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001833 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001834 final int requestId = nri.getActiveRequest() != null
1835 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001836 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001837 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001838 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001839 }
1840
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001841 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001842 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001843 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001844 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001845 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001846 @NonNull
1847 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1848 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001849 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1850 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1851 // but only exists if an app asks about them or requests them. Ensure the requesting app
1852 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001853 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001854 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1855 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1856 null /* extraInfo */);
1857 }
1858 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001859 return filtered;
1860 }
1861
1862 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1863 boolean ignoreBlocked) {
1864 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1865 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001866 }
1867
1868 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001869 * Return NetworkInfo for the active (i.e., connected) network interface.
1870 * It is assumed that at most one network is active at a time. If more
1871 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07001872 * @return the info for the active network, or {@code null} if none is
1873 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08001874 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001875 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001876 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001877 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001878 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001879 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09001880 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1881 if (nai == null) return null;
1882 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1883 maybeLogBlockedNetworkInfo(networkInfo, uid);
1884 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08001885 }
1886
Paul Jensen1f567382015-02-13 14:18:39 -05001887 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001888 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05001889 public Network getActiveNetwork() {
1890 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001891 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00001892 }
1893
1894 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001895 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001896 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001897 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001898 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00001899 }
1900
Chalard Jean46bfbf02022-02-02 00:56:25 +09001901 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001902 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001903 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
1904 if (vpnNai != null) {
1905 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
1906 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
1907 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09001908 }
Paul Jensen1f567382015-02-13 14:18:39 -05001909 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001910
James Mattis2516da32021-01-31 17:06:19 -08001911 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001912 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
1913 ignoreBlocked)) {
1914 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001915 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09001916 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05001917 }
1918
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001919 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001920 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001921 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08001922 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001923 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1924 if (nai == null) return null;
1925 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001926 }
1927
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001928 /** Returns a NetworkInfo object for a network that doesn't exist. */
1929 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
1930 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
1931 getNetworkTypeName(networkType), "" /* subtypeName */);
1932 info.setIsAvailable(true);
1933 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
1934 // background data is restricted.
1935 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
1936 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
1937 ? DetailedState.BLOCKED
1938 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001939 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
1940 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001941 return info;
1942 }
1943
Lorenzo Colittia7574052021-01-19 01:33:05 +09001944 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001945 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
1946 return null;
1947 }
1948 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09001949 if (nai == null) {
1950 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001951 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001952 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
1953 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09001954 }
1955
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001956 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001957 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08001958 public NetworkInfo getNetworkInfo(int networkType) {
1959 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001960 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001961 if (getVpnUnderlyingNetworks(uid) != null) {
1962 // A VPN is active, so we may need to return one of its underlying networks. This
1963 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09001964 // getNetworkAgentInfoForUid.
1965 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
1966 if (nai == null) return null;
1967 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
1968 if (networkInfo.getType() == networkType) {
1969 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001970 }
1971 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001972 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001973 }
1974
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001975 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001976 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001977 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001978 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001979 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001980 if (nai == null) return null;
1981 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001982 }
1983
1984 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08001985 public NetworkInfo[] getAllNetworkInfo() {
1986 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08001987 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04001988 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1989 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001990 NetworkInfo info = getNetworkInfo(networkType);
1991 if (info != null) {
1992 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001993 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001994 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07001995 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08001996 }
1997
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07001998 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09001999 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002000 public Network getNetworkForType(int networkType) {
2001 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002002 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2003 return null;
2004 }
2005 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2006 if (nai == null) {
2007 return null;
2008 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002009 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002010 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2011 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002012 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002013 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002014 }
2015
2016 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002017 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002018 public Network[] getAllNetworks() {
2019 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002020 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002021 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002022 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002023 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002024 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002025 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002026 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002027 }
2028
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002029 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002030 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002031 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002032 // The basic principle is: if an app's traffic could possibly go over a
2033 // network, without the app doing anything multinetwork-specific,
2034 // (hence, by "default"), then include that network's capabilities in
2035 // the array.
2036 //
2037 // In the normal case, app traffic only goes over the system's default
2038 // network connection, so that's the only network returned.
2039 //
2040 // With a VPN in force, some app traffic may go into the VPN, and thus
2041 // over whatever underlying networks the VPN specifies, while other app
2042 // traffic may go over the system default network (e.g.: a split-tunnel
2043 // VPN, or an app disallowed by the VPN), so the set of networks
2044 // returned includes the VPN's underlying networks and the system
2045 // default.
2046 enforceAccessPermission();
2047
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002048 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002049
James Mattis2516da32021-01-31 17:06:19 -08002050 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2051 if (!nri.isBeingSatisfied()) {
2052 continue;
2053 }
2054 final NetworkAgentInfo nai = nri.getSatisfier();
2055 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2056 if (null != nc
2057 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2058 && !result.containsKey(nai.network)) {
2059 result.put(
2060 nai.network,
2061 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002062 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002063 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2064 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002065 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002066 }
2067
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002068 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002069 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002070 if (null != networks) {
2071 for (final Network network : networks) {
2072 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2073 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002074 result.put(
2075 network,
2076 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002077 nc,
2078 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002079 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002080 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002081 }
2082 }
2083 }
2084
2085 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2086 out = result.values().toArray(out);
2087 return out;
2088 }
2089
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002090 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002091 public boolean isNetworkSupported(int networkType) {
2092 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002093 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002094 }
2095
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002096 /**
2097 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002098 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002099 * @return the ip properties for the active network, or {@code null} if
2100 * none is active
2101 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002102 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002103 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002104 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002105 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002106 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2107 if (nai == null) return null;
2108 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002109 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002110 }
2111
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002112 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002113 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002114 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002115 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002116 final LinkProperties lp = getLinkProperties(nai);
2117 if (lp == null) return null;
2118 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002119 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002120 }
2121
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002122 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002123 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002124 public LinkProperties getLinkProperties(Network network) {
2125 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002126 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2127 if (lp == null) return null;
2128 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002129 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002130 }
2131
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002132 @Nullable
2133 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002134 if (nai == null) {
2135 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002136 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002137 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002138 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002139 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002140 }
2141
lucaslinc582d502022-01-27 09:07:00 +08002142 @Override
2143 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002144 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002145 @NonNull String packageName, @Nullable String callingAttributionTag) {
2146 Objects.requireNonNull(packageName);
2147 Objects.requireNonNull(lp);
2148 enforceNetworkStackOrSettingsPermission();
2149 if (!checkAccessPermission(-1 /* pid */, uid)) {
2150 return null;
2151 }
2152 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2153 }
2154
Qingxi Lib2748102020-01-08 12:51:49 -08002155 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2156 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2157 }
2158
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002159 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002160 if (nai == null) return null;
2161 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002162 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002163 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002164 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002165 }
2166
2167 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002168 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2169 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002170 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002171 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002172 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002173 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002174 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002175 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002176 }
2177
lucaslinc582d502022-01-27 09:07:00 +08002178 @Override
lucaslind2b06132022-03-02 10:56:57 +08002179 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2180 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2181 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002182 Objects.requireNonNull(nc);
2183 Objects.requireNonNull(packageName);
2184 enforceNetworkStackOrSettingsPermission();
2185 if (!checkAccessPermission(-1 /* pid */, uid)) {
2186 return null;
2187 }
2188 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2189 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2190 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2191 callingAttributionTag);
2192 }
2193
lucaslin69e1aa92022-03-22 18:15:09 +08002194 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2195 if (nc.getUnderlyingNetworks() != null
2196 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2197 nc.setUnderlyingNetworks(null);
2198 }
2199 }
2200
Qingxi Libb8da982020-01-17 17:54:27 -08002201 @VisibleForTesting
2202 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002203 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002204 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2205 // this would be expensive (one more permission check every time any NC callback is
2206 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2207 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2208 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002209 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002210 if (!checkSettingsPermission(callerPid, callerUid)) {
2211 newNc.setUids(null);
2212 newNc.setSSID(null);
2213 }
Etan Cohen107ae952018-12-30 17:59:59 -08002214 if (newNc.getNetworkSpecifier() != null) {
2215 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2216 }
Benedict Wonga5604ea2021-07-09 00:13:45 -07002217 if (!checkAnyPermissionOf(callerPid, callerUid, android.Manifest.permission.NETWORK_STACK,
2218 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2219 newNc.setAdministratorUids(new int[0]);
2220 }
Benedict Wong53de25f2021-03-24 14:01:51 -07002221 if (!checkAnyPermissionOf(
2222 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002223 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002224 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002225 }
lucaslin69e1aa92022-03-22 18:15:09 +08002226 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002227
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002228 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002229 }
2230
Roshan Pius98f59ec2021-02-23 08:47:39 -08002231 /**
2232 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002233 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002234 * NetworkCapabilities.
2235 * Note: This wrapper does not support any sort of invalidation and thus must not be
2236 * persistent or long-lived. It may only be used for the time necessary to
2237 * compute the redactions required by one particular NetworkCallback or
2238 * synchronous call.
2239 */
2240 private class RedactionPermissionChecker {
2241 private final int mCallingPid;
2242 private final int mCallingUid;
2243 @NonNull private final String mCallingPackageName;
2244 @Nullable private final String mCallingAttributionTag;
2245
2246 private Boolean mHasLocationPermission = null;
2247 private Boolean mHasLocalMacAddressPermission = null;
2248 private Boolean mHasSettingsPermission = null;
2249
2250 RedactionPermissionChecker(int callingPid, int callingUid,
2251 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2252 mCallingPid = callingPid;
2253 mCallingUid = callingUid;
2254 mCallingPackageName = callingPackageName;
2255 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002256 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002257
2258 private boolean hasLocationPermissionInternal() {
2259 final long token = Binder.clearCallingIdentity();
2260 try {
2261 return mLocationPermissionChecker.checkLocationPermission(
2262 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2263 null /* message */);
2264 } finally {
2265 Binder.restoreCallingIdentity(token);
2266 }
2267 }
2268
2269 /**
2270 * Returns whether the app holds location permission or not (might return cached result
2271 * if the permission was already checked before).
2272 */
2273 public boolean hasLocationPermission() {
2274 if (mHasLocationPermission == null) {
2275 // If there is no cached result, perform the check now.
2276 mHasLocationPermission = hasLocationPermissionInternal();
2277 }
2278 return mHasLocationPermission;
2279 }
2280
2281 /**
2282 * Returns whether the app holds local mac address permission or not (might return cached
2283 * result if the permission was already checked before).
2284 */
2285 public boolean hasLocalMacAddressPermission() {
2286 if (mHasLocalMacAddressPermission == null) {
2287 // If there is no cached result, perform the check now.
2288 mHasLocalMacAddressPermission =
2289 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2290 }
2291 return mHasLocalMacAddressPermission;
2292 }
2293
2294 /**
2295 * Returns whether the app holds settings permission or not (might return cached
2296 * result if the permission was already checked before).
2297 */
2298 public boolean hasSettingsPermission() {
2299 if (mHasSettingsPermission == null) {
2300 // If there is no cached result, perform the check now.
2301 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2302 }
2303 return mHasSettingsPermission;
2304 }
2305 }
2306
2307 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2308 @NetworkCapabilities.NetCapability long redaction) {
2309 return (redactions & redaction) != 0;
2310 }
2311
2312 /**
2313 * Use the provided |applicableRedactions| to check the receiving app's
2314 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2315 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2316 * before being sent to the corresponding app.
2317 */
2318 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2319 @NetworkCapabilities.RedactionType long applicableRedactions,
2320 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2321 boolean includeLocationSensitiveInfo) {
2322 long redactions = applicableRedactions;
2323 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2324 if (includeLocationSensitiveInfo
2325 && redactionPermissionChecker.hasLocationPermission()) {
2326 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2327 }
2328 }
2329 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2330 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2331 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2332 }
2333 }
2334 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2335 if (redactionPermissionChecker.hasSettingsPermission()) {
2336 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2337 }
2338 }
2339 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002340 }
2341
Qingxi Lib2748102020-01-08 12:51:49 -08002342 @VisibleForTesting
2343 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002344 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002345 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002346 int callingPid, int callingUid, @NonNull String callingPkgName,
2347 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002348 if (nc == null) {
2349 return null;
2350 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002351 // Avoid doing location permission check if the transport info has no location sensitive
2352 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002353 final RedactionPermissionChecker redactionPermissionChecker =
2354 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2355 callingAttributionTag);
2356 final long redactions = retrieveRequiredRedactions(
2357 nc.getApplicableRedactions(), redactionPermissionChecker,
2358 includeLocationSensitiveInfo);
2359 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002360 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002361 // TODO : calling UID is redacted because apps should generally not know what UID is
2362 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002363 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002364 newNc.setOwnerUid(INVALID_UID);
2365 return newNc;
2366 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002367 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2368 if (nc.hasTransport(TRANSPORT_VPN)) {
2369 // Owner UIDs already checked above. No need to re-check.
2370 return newNc;
2371 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002372 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2373 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002374 // compatibility for older apps.
2375 if (!includeLocationSensitiveInfo
2376 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002377 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002378 newNc.setOwnerUid(INVALID_UID);
2379 return newNc;
2380 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002381 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002382 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002383 newNc.setOwnerUid(INVALID_UID);
2384 }
Qingxi Lib2748102020-01-08 12:51:49 -08002385 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002386 }
2387
lucaslinc582d502022-01-27 09:07:00 +08002388 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002389 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2390 LinkProperties lp, int callerPid, int callerUid) {
2391 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002392 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2393 // this would be expensive (one more permission check every time any LP callback is
2394 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2395 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2396 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002397
2398 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2399 final boolean needsSanitization =
2400 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2401 if (!needsSanitization) {
2402 return new LinkProperties(lp);
2403 }
2404
2405 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002406 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002407 }
2408
2409 final LinkProperties newLp = new LinkProperties(lp);
2410 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2411 // object gets parceled.
2412 newLp.setCaptivePortalApiUrl(null);
2413 newLp.setCaptivePortalData(null);
2414 return newLp;
2415 }
2416
Roshan Pius08c94fb2020-01-16 12:17:17 -08002417 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2418 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002419 // There is no need to track the effective UID of the request here. If the caller
2420 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002421 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002422 // Unprivileged apps can only pass in null or their own UID.
2423 if (nc.getUids() == null) {
2424 // If the caller passes in null, the callback will also match networks that do not
2425 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2426 // In this case, redact everything in the request immediately. This ensures that the
2427 // app is not able to get any redacted information by filing an unredacted request
2428 // and observing whether the request matches something.
2429 if (nc.getNetworkSpecifier() != null) {
2430 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2431 }
2432 } else {
2433 nc.setSingleUid(callerUid);
2434 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002435 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002436 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002437 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002438
2439 // Clear owner UID; this can never come from an app.
2440 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002441 }
2442
Chalard Jean38354d12018-03-20 19:13:57 +09002443 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002444 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002445 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2446 }
2447 }
2448
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002449 @Override
2450 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2451 enforceAccessPermission();
2452 final int callerUid = Binder.getCallingUid();
2453 final long token = Binder.clearCallingIdentity();
2454 try {
2455 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2456 } finally {
2457 Binder.restoreCallingIdentity(token);
2458 }
2459 }
2460
junyulaiebd15162021-03-03 12:09:05 +08002461 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002462 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002463 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002464 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002465 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002466
Serik Beketayev05130302021-01-15 16:47:25 -08002467 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002468 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002469 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2470 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002471 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002472 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002473 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002474 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2475 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002476 }
2477 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002478 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002479 }
2480
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002481 @Override
junyulaiebd15162021-03-03 12:09:05 +08002482 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002483 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002484 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002485 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002486
2487 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2488 for (Network network : getAllNetworks()) {
2489 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002490 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002491 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2492 // NetworkCapabilities, which may contain UIDs of apps to which the
2493 // network applies. Should the UIDs be cleared so as not to leak or
2494 // interfere ?
2495 result.add(nai.getNetworkStateSnapshot());
2496 }
2497 }
2498 return result;
2499 }
2500
2501 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002502 public boolean isActiveNetworkMetered() {
2503 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002504
Qingxi Lib2748102020-01-08 12:51:49 -08002505 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002506 if (caps != null) {
2507 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2508 } else {
2509 // Always return the most conservative value
2510 return true;
2511 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002512 }
2513
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002514 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002515 * Ensures that the system cannot call a particular method.
2516 */
2517 private boolean disallowedBecauseSystemCaller() {
2518 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002519 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2520 // for devices launched with Q and above. However, existing devices upgrading to Q and
2521 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002522 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002523 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002524 log("This method exists only for app backwards compatibility"
2525 + " and must not be called by system services.");
2526 return true;
2527 }
2528 return false;
2529 }
2530
paulhub2c28682021-08-18 18:35:54 +08002531 private int getAppUid(final String app, final UserHandle user) {
2532 final PackageManager pm =
2533 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2534 final long token = Binder.clearCallingIdentity();
2535 try {
2536 return pm.getPackageUid(app, 0 /* flags */);
2537 } catch (PackageManager.NameNotFoundException e) {
2538 return -1;
2539 } finally {
2540 Binder.restoreCallingIdentity(token);
2541 }
2542 }
2543
2544 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2545 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2546 if (getAppUid(packageName, user) != callingUid) {
2547 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2548 }
2549 }
2550
Lorenzo Colitti23862912018-09-28 11:31:55 +09002551 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002552 * Ensure that a network route exists to deliver traffic to the specified
2553 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002554 * @param networkType the type of the network over which traffic to the
2555 * specified host is to be routed
2556 * @param hostAddress the IP address of the host to which the route is
2557 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002558 * @return {@code true} on success, {@code false} on failure
2559 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002560 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002561 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2562 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002563 if (disallowedBecauseSystemCaller()) {
2564 return false;
2565 }
paulhub2c28682021-08-18 18:35:54 +08002566 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002567 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002568 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002569 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002570 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002571
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002572 InetAddress addr;
2573 try {
2574 addr = InetAddress.getByAddress(hostAddress);
2575 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002576 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002577 return false;
2578 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002579
The Android Open Source Project28527d22009-03-03 19:31:44 -08002580 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002581 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002582 return false;
2583 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002584
2585 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2586 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002587 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002588 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2589 } else {
2590 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2591 }
2592 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002593 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002594
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002595 DetailedState netState;
2596 synchronized (nai) {
2597 netState = nai.networkInfo.getDetailedState();
2598 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002599
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002600 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002601 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002602 log("requestRouteToHostAddress on down network "
2603 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002604 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002605 }
2606 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002607 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002608
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002609 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002610 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002611 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002612 LinkProperties lp;
2613 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002614 synchronized (nai) {
2615 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002616 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002617 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002618 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002619 if (DBG) {
2620 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2621 }
Wink Saville32506bc2013-06-29 21:10:57 -07002622 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002623 } finally {
2624 Binder.restoreCallingIdentity(token);
2625 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002626 }
2627
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002628 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002629 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002630 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002631 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002632 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002633 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002634 if (bestRoute.getGateway().equals(addr)) {
2635 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002636 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002637 } else {
2638 // if we will connect to this through another route, add a direct route
2639 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002640 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002641 }
2642 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002643 if (DBG) log("Adding legacy route " + bestRoute +
2644 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002645
2646 final String dst = bestRoute.getDestinationLinkAddress().toString();
2647 final String nextHop = bestRoute.hasGateway()
2648 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002649 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002650 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2651 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002652 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002653 return false;
2654 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002655 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002656 }
2657
paulhu7c0a2e62021-01-08 00:51:49 +08002658 class DnsResolverUnsolicitedEventCallback extends
2659 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002660 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002661 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002662 try {
2663 mHandler.sendMessage(mHandler.obtainMessage(
2664 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002665 new PrivateDnsValidationUpdate(event.netId,
2666 InetAddresses.parseNumericAddress(event.ipAddress),
2667 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002668 } catch (IllegalArgumentException e) {
2669 loge("Error parsing ip address in validation event");
2670 }
2671 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002672
2673 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002674 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2675 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002676 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2677 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2678 // event callback for certain nai. e.g. cellular. Register here to pass to
2679 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002680 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002681 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2682 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002683 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002684 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002685 }
2686 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002687
2688 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002689 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2690 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2691 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002692 }
dalyk1720e542018-03-05 12:42:22 -05002693
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002694 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002695 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002696 return this.VERSION;
2697 }
2698
2699 @Override
2700 public String getInterfaceHash() {
2701 return this.HASH;
2702 }
paulhu7c0a2e62021-01-08 00:51:49 +08002703 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002704
2705 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002706 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2707 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002708
paulhu7c0a2e62021-01-08 00:51:49 +08002709 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002710 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002711 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002712 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002713 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002714 }
2715 }
2716
Sudheer Shanka9967d462021-03-18 19:09:25 +00002717 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002718 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002719 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002720 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2721 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002722 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002723 };
2724
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002725 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002726 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002727 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002728 }
2729
paulhu1a407652019-03-22 16:35:06 +08002730 private boolean checkAnyPermissionOf(int pid, int uid, String... permissions) {
2731 for (String permission : permissions) {
2732 if (mContext.checkPermission(permission, pid, uid) == PERMISSION_GRANTED) {
2733 return true;
2734 }
2735 }
2736 return false;
2737 }
2738
Paul Jensen83f5d572014-08-29 09:54:01 -04002739 private void enforceInternetPermission() {
2740 mContext.enforceCallingOrSelfPermission(
2741 android.Manifest.permission.INTERNET,
2742 "ConnectivityService");
2743 }
2744
The Android Open Source Project28527d22009-03-03 19:31:44 -08002745 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002746 mContext.enforceCallingOrSelfPermission(
2747 android.Manifest.permission.ACCESS_NETWORK_STATE,
2748 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002749 }
2750
lucaslinc582d502022-01-27 09:07:00 +08002751 private boolean checkAccessPermission(int pid, int uid) {
2752 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2753 == PERMISSION_GRANTED;
2754 }
2755
paulhua6ee2122021-02-22 15:40:43 +08002756 /**
2757 * Performs a strict and comprehensive check of whether a calling package is allowed to
2758 * change the state of network, as the condition differs for pre-M, M+, and
2759 * privileged/preinstalled apps. The caller is expected to have either the
2760 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2761 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2762 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2763 * permission and cannot be revoked. See http://b/23597341
2764 *
2765 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2766 * of this app will be updated to the current time.
2767 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002768 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002769 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2770 == PackageManager.PERMISSION_GRANTED) {
2771 return;
2772 }
2773
2774 if (callingPkg == null) {
2775 throw new SecurityException("Calling package name is null.");
2776 }
2777
2778 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2779 final int uid = mDeps.getCallingUid();
2780 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2781 callingPkg, callingAttributionTag, null /* message */);
2782
2783 if (mode == AppOpsManager.MODE_ALLOWED) {
2784 return;
2785 }
2786
2787 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2788 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2789 return;
2790 }
2791
2792 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2793 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2794 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002795 }
2796
Charles He9369e612017-05-15 17:07:18 +01002797 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002798 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002799 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002800 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002801 }
2802
paulhu8e96a752019-08-12 16:25:11 +08002803 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002804 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002805 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002806 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002807 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002808 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002809 }
2810
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002811 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002812 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002813 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002814 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002815 android.Manifest.permission.NETWORK_SETTINGS,
2816 android.Manifest.permission.NETWORK_FACTORY,
2817 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2818 }
2819
2820 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002821 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002822 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002823 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002824 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2825 android.Manifest.permission.NETWORK_FACTORY,
2826 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2827 }
2828
lucaslin69e1aa92022-03-22 18:15:09 +08002829 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2830 return PERMISSION_GRANTED == mContext.checkPermission(
2831 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2832 || PERMISSION_GRANTED == mContext.checkPermission(
2833 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2834 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002835 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002836 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002837 }
2838
Chalard Jean9a396cc2018-02-21 18:43:54 +09002839 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002840 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002841 android.Manifest.permission.NETWORK_SETTINGS,
2842 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002843 }
2844
2845 private boolean checkSettingsPermission(int pid, int uid) {
2846 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002847 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2848 || PERMISSION_GRANTED == mContext.checkPermission(
2849 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002850 }
2851
paulhu8e96a752019-08-12 16:25:11 +08002852 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002853 enforceNetworkStackPermissionOr(mContext,
2854 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002855 }
2856
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002857 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002858 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002859 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002860 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002861 }
2862
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002863 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002864 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002865 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2866 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002867 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002868 }
2869
James Mattis8378aec2021-01-26 14:05:36 -08002870 private void enforceOemNetworkPreferencesPermission() {
2871 mContext.enforceCallingOrSelfPermission(
2872 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
2873 "ConnectivityService");
2874 }
2875
James Mattisfa270db2021-05-31 17:11:10 -07002876 private void enforceManageTestNetworksPermission() {
2877 mContext.enforceCallingOrSelfPermission(
2878 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2879 "ConnectivityService");
2880 }
2881
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002882 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002883 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002884 android.Manifest.permission.NETWORK_STACK,
2885 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07002886 }
2887
Cody Kesting83bb5fa2020-01-05 14:06:39 -08002888 private boolean checkNetworkStackPermission(int pid, int uid) {
2889 return checkAnyPermissionOf(pid, uid,
2890 android.Manifest.permission.NETWORK_STACK,
2891 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2892 }
2893
paulhu1a407652019-03-22 16:35:06 +08002894 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
2895 return checkAnyPermissionOf(pid, uid,
2896 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09002897 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2898 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08002899 }
2900
Paul Hu8fc2a552022-05-04 18:44:42 +08002901 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
2902 boolean checkUidsAllowedList) {
2903 if (PermissionUtils.checkAnyPermissionOf(mContext,
2904 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
2905 return true;
2906 }
2907
2908 // fallback to ConnectivityInternalPermission
2909 // TODO: Remove this fallback check after all apps have declared
2910 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
2911 if (PermissionUtils.checkAnyPermissionOf(mContext,
2912 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
2913 return true;
2914 }
2915
2916 // Check whether uid is in allowed on restricted networks list.
2917 if (checkUidsAllowedList
2918 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
2919 return true;
2920 }
2921 return false;
2922 }
2923
2924 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
2925 final int callingUid = mDeps.getCallingUid();
2926 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
2927 throw new SecurityException("ConnectivityService: user " + callingUid
2928 + " has no permission to access restricted network.");
2929 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09002930 }
2931
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002932 private void enforceKeepalivePermission() {
Lorenzo Colittif25beee2015-09-08 13:21:48 +09002933 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09002934 }
2935
Roshan Pius98f59ec2021-02-23 08:47:39 -08002936 private boolean checkLocalMacAddressPermission(int pid, int uid) {
2937 return PERMISSION_GRANTED == mContext.checkPermission(
2938 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
2939 }
2940
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002941 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002942 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002943 }
2944
2945 private void sendInetConditionBroadcast(NetworkInfo info) {
2946 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
2947 }
2948
Wink Saville4f0de1e2011-08-04 15:01:58 -07002949 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07002950 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07002951 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07002952 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002953 if (info.isFailover()) {
2954 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
2955 info.setFailover(false);
2956 }
2957 if (info.getReason() != null) {
2958 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
2959 }
2960 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002961 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
2962 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08002963 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07002964 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07002965 return intent;
2966 }
2967
2968 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
2969 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
2970 }
2971
Chiachang Wang3bc52762021-11-25 14:17:57 +08002972 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
2973 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002974 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09002975 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09002976 if (!mSystemReady
2977 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08002978 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04002979 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08002980 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09002981 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07002982 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07002983 }
2984
Dianne Hackborn66dd0332015-12-09 17:22:26 -08002985 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07002986 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002987 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07002988 final NetworkInfo ni = intent.getParcelableExtra(
2989 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08002990 final BroadcastOptions opts = BroadcastOptions.makeBasic();
2991 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
2992 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08002993 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08002994 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07002995 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00002996 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07002997 } finally {
2998 Binder.restoreCallingIdentity(ident);
2999 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003000 }
3001 }
3002
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003003 /**
Aaron Huang96011892020-06-27 07:18:23 +08003004 * Called by SystemServer through ConnectivityManager when the system is ready.
3005 */
3006 @Override
3007 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003008 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003009 throw new SecurityException("Calling Uid is not system uid.");
3010 }
3011 systemReadyInternal();
3012 }
3013
3014 /**
3015 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003016 */
3017 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003018 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003019 // Load flags after PackageManager is ready to query module version
3020 mFlags.loadFlags(mDeps, mContext);
3021
Aaron Huang9a57acf2020-12-08 10:03:29 +08003022 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3023 // listening network request which is sent by MultipathPolicyTracker won't be added
3024 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3025 // be called after PermissionMonitor#startMonitoring().
3026 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3027 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3028 // to ensure the tracking will be initialized correctly.
paulhuc62d3c22019-11-19 17:55:31 +08003029 mPermissionMonitor.startMonitoring();
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003030 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003031 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003032
Hugo Benichie5220992017-04-26 14:53:28 +09003033 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003034 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003035 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003036 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003037 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003038 }
3039 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003040
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003041 // Create network requests for always-on networks.
3042 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003043
3044 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003045 // Note that updating can be skipped here if the list is empty only because no uid
3046 // rules are applied before system ready. Normally, the empty uid list means to clear
3047 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003048 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3049 updateMobileDataPreferredUids();
3050 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003051
3052 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3053 if (SdkLevel.isAtLeastT()) {
3054 mBpfNetMaps.setPullAtomCallback(mContext);
3055 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003056 }
3057
The Android Open Source Project28527d22009-03-03 19:31:44 -08003058 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003059 * Start listening for default data network activity state changes.
3060 */
3061 @Override
3062 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003063 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003064 }
3065
3066 /**
3067 * Stop listening for default data network activity state changes.
3068 */
3069 @Override
3070 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003071 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003072 }
3073
3074 /**
3075 * Check whether the default network radio is currently active.
3076 */
3077 @Override
3078 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003079 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003080 }
3081
3082 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003083 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003084 * and set it on it's iface.
3085 */
Junyu Lai970963e2022-10-25 15:46:47 +08003086 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003087 final String iface = newLp.getInterfaceName();
3088 final int mtu = newLp.getMtu();
Pierre Imai07c53a32016-02-08 16:01:40 +09003089 if (oldLp == null && mtu == 0) {
3090 // Silently ignore unset MTU value.
3091 return;
3092 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003093 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
3094 if (VDBG) log("identical MTU - not setting");
3095 return;
3096 }
paulhucbbc3db2019-03-08 16:35:20 +08003097 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003098 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003099 return;
3100 }
sy.yun4aa73922013-09-02 05:24:09 +09003101
w19976e714f1d2014-08-05 15:18:11 -07003102 // Cannot set MTU without interface name
3103 if (TextUtils.isEmpty(iface)) {
3104 loge("Setting MTU size with null iface.");
3105 return;
3106 }
3107
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003108 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003109 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003110 mNetd.interfaceSetMtu(iface, mtu);
3111 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003112 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003113 }
3114 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003115
Chenbo Feng15416292018-11-08 17:36:21 -08003116 @VisibleForTesting
3117 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003118
Junyu Lai970963e2022-10-25 15:46:47 +08003119 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003120 String[] values = null;
3121 if (tcpBufferSizes != null) {
3122 values = tcpBufferSizes.split(",");
3123 }
3124
3125 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003126 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003127 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3128 values = tcpBufferSizes.split(",");
3129 }
3130
3131 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3132
3133 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003134 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003135
Chenbo Feng15416292018-11-08 17:36:21 -08003136 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3137 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3138 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003139 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003140 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003141 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003142 }
3143 }
3144
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003145 @Override
3146 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003147 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003148 NETWORK_RESTORE_DELAY_PROP_NAME);
3149 if(restoreDefaultNetworkDelayStr != null &&
3150 restoreDefaultNetworkDelayStr.length() != 0) {
3151 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003152 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003153 } catch (NumberFormatException e) {
3154 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003155 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003156 // if the system property isn't set, use the value for the apn type
3157 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3158
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003159 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3160 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003161 }
3162 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003163 }
3164
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003165 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003166 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003167 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003168 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003169 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003170 // Start gathering diagnostic information.
3171 netDiags.add(new NetworkDiagnostics(
3172 nai.network,
3173 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003174 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003175 DIAG_TIME_MS));
3176 }
3177
3178 for (NetworkDiagnostics netDiag : netDiags) {
3179 pw.println();
3180 netDiag.waitForMeasurements();
3181 netDiag.dump(pw);
3182 }
3183 }
3184
The Android Open Source Project28527d22009-03-03 19:31:44 -08003185 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003186 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3187 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003188 if (!checkDumpPermission(mContext, TAG, writer)) return;
3189
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003190 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003191 }
3192
lucaslin99473f62020-12-10 15:10:54 +08003193 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3194 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3195 != PackageManager.PERMISSION_GRANTED) {
3196 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003197 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003198 + " due to missing android.permission.DUMP permission");
3199 return false;
3200 } else {
3201 return true;
3202 }
3203 }
3204
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003205 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003206 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003207
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003208 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003209 dumpNetworkDiagnostics(pw);
3210 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003211 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003212 dumpNetworks(pw);
3213 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003214 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003215 dumpNetworkRequests(pw);
3216 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003217 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3218 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3219 dumpTrafficController(pw, fd, verbose);
3220 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003221 }
Erik Kline9647f382015-06-05 17:47:34 +09003222
Junyu Lai0da479b2022-04-20 15:06:29 +08003223 pw.println("NetworkProviders for:");
3224 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003225 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003226 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003227 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003228 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003229 pw.println();
3230
Chalard Jean5b409c72021-02-04 13:12:59 +09003231 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003232 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003233 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003234 pw.println("none");
3235 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003236 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003237 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003238 pw.println();
3239
James Mattis8b298a02021-06-01 22:34:04 -07003240 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003241 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003242 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003243 pw.decreaseIndent();
3244 pw.println();
3245
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003246 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003247 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003248 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003249 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003250 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003251
junyulaif2c67e42018-08-07 19:50:45 +08003252 pw.println("Status for known UIDs:");
3253 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003254 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003255 for (int i = 0; i < size; i++) {
3256 // Don't crash if the array is modified while dumping in bugreports.
3257 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003258 final int uid = mUidBlockedReasons.keyAt(i);
3259 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3260 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003261 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003262 } catch (ArrayIndexOutOfBoundsException e) {
3263 pw.println(" ArrayIndexOutOfBoundsException");
3264 } catch (ConcurrentModificationException e) {
3265 pw.println(" ConcurrentModificationException");
3266 }
3267 }
3268 pw.println();
3269 pw.decreaseIndent();
3270
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003271 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003272 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003273 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003274 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003275 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003276
Junyu Lai0da479b2022-04-20 15:06:29 +08003277 pw.println("Network Offers:");
3278 pw.increaseIndent();
3279 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3280 pw.println(offerInfo.offer);
3281 }
3282 pw.decreaseIndent();
3283 pw.println();
3284
Robert Greenwalt94e22142014-07-30 16:31:24 -07003285 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003286
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003287 pw.println();
markchien5e866652019-09-30 14:40:57 +08003288 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003289
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003290 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003291 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003292
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003293 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003294
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003295 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003296 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003297 pw.println("mNetworkRequestInfoLogs (most recent first):");
3298 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003299 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003300 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003301
3302 pw.println();
3303 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3304 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003305 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003306 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003307
3308 pw.println();
3309 pw.println("NetTransition WakeLock activity (most recent first):");
3310 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003311 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3312 pw.println("total releases: " + mTotalWakelockReleases);
3313 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3314 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3315 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3316 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3317 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3318 }
James Mattiscb1e0362021-04-06 17:07:42 -07003319 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003320
3321 pw.println();
3322 pw.println("bandwidth update requests (by uid):");
3323 pw.increaseIndent();
3324 synchronized (mBandwidthRequests) {
3325 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3326 pw.println("[" + mBandwidthRequests.keyAt(i)
3327 + "]: " + mBandwidthRequests.valueAt(i));
3328 }
3329 }
3330 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003331 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003332
James Mattiscb1e0362021-04-06 17:07:42 -07003333 pw.println();
3334 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3335 pw.increaseIndent();
3336 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003337 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003338 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003339
3340 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003341
3342 pw.println();
3343 pw.println("Permission Monitor:");
3344 pw.increaseIndent();
3345 mPermissionMonitor.dump(pw);
3346 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003347
3348 pw.println();
3349 pw.println("Legacy network activity:");
3350 pw.increaseIndent();
3351 mNetworkActivityTracker.dump(pw);
3352 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003353 }
3354
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003355 private void dumpNetworks(IndentingPrintWriter pw) {
3356 for (NetworkAgentInfo nai : networksSortedById()) {
3357 pw.println(nai.toString());
3358 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003359 pw.println("Nat464Xlat:");
3360 pw.increaseIndent();
3361 nai.dumpNat464Xlat(pw);
3362 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003363 pw.println(String.format(
3364 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3365 nai.numForegroundNetworkRequests(),
3366 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3367 nai.numBackgroundNetworkRequests(),
3368 nai.numNetworkRequests()));
3369 pw.increaseIndent();
3370 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3371 pw.println(nai.requestAt(i).toString());
3372 }
3373 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003374 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003375 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003376 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003377 pw.decreaseIndent();
3378 pw.decreaseIndent();
3379 }
3380 }
3381
James Mattis8b298a02021-06-01 22:34:04 -07003382 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3383 if (!mProfileNetworkPreferences.isEmpty()) {
3384 pw.println("Profile preferences:");
3385 pw.increaseIndent();
3386 pw.println(mProfileNetworkPreferences.preferences);
3387 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003388 }
James Mattis8b298a02021-06-01 22:34:04 -07003389 if (!mOemNetworkPreferences.isEmpty()) {
3390 pw.println("OEM preferences:");
3391 pw.increaseIndent();
3392 pw.println(mOemNetworkPreferences);
3393 pw.decreaseIndent();
3394 }
3395 if (!mMobileDataPreferredUids.isEmpty()) {
3396 pw.println("Mobile data preferred UIDs:");
3397 pw.increaseIndent();
3398 pw.println(mMobileDataPreferredUids);
3399 pw.decreaseIndent();
3400 }
James Mattis45d81842021-01-10 14:24:24 -08003401
James Mattis8b298a02021-06-01 22:34:04 -07003402 pw.println("Default requests:");
3403 pw.increaseIndent();
3404 dumpPerAppDefaultRequests(pw);
3405 pw.decreaseIndent();
3406 }
3407
3408 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003409 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3410 if (mDefaultRequest == defaultRequest) {
3411 continue;
3412 }
3413
James Mattis8b298a02021-06-01 22:34:04 -07003414 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3415 final String networkOutput;
3416 if (null == satisfier) {
3417 networkOutput = "null";
3418 } else if (mNoServiceNetwork.equals(satisfier)) {
3419 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003420 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003421 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003422 }
James Mattis8b298a02021-06-01 22:34:04 -07003423 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3424 ? "" : " asUid: " + defaultRequest.mAsUid;
3425 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3426 + defaultRequest.mPid + asUidString + "]";
3427 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3428 + " Preference order: " + defaultRequest.mPreferenceOrder
3429 + " Tracked UIDs: " + defaultRequest.getUids();
3430 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003431 }
3432 }
3433
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003434 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003435 NetworkRequestInfo[] infos = null;
3436 while (infos == null) {
3437 try {
3438 infos = requestsSortedById();
3439 } catch (ConcurrentModificationException e) {
3440 // mNetworkRequests should only be accessed from handler thread, except dump().
3441 // As dump() is never called in normal usage, it would be needlessly expensive
3442 // to lock the collection only for its benefit. Instead, retry getting the
3443 // requests if ConcurrentModificationException is thrown during dump().
3444 }
3445 }
3446 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003447 pw.println(nri.toString());
3448 }
3449 }
3450
Ken Chene6d511f2022-01-25 11:10:42 +08003451 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3452 boolean verbose) {
3453 try {
3454 mBpfNetMaps.dump(fd, verbose);
3455 } catch (ServiceSpecificException e) {
3456 pw.println(e.getMessage());
3457 } catch (IOException e) {
3458 loge("Dump BPF maps failed, " + e);
3459 }
3460 }
3461
Chalard Jean524f0b12021-10-25 21:11:56 +09003462 private void dumpAllRequestInfoLogsToLogcat() {
3463 try (PrintWriter logPw = new PrintWriter(new Writer() {
3464 @Override
3465 public void write(final char[] cbuf, final int off, final int len) {
3466 // This method is called with 0-length and 1-length arrays for empty strings
3467 // or strings containing only the DEL character.
3468 if (len <= 1) return;
3469 Log.e(TAG, new String(cbuf, off, len));
3470 }
3471 @Override public void flush() {}
3472 @Override public void close() {}
3473 })) {
3474 mNetworkRequestInfoLogs.dump(logPw);
3475 }
3476 }
3477
Hugo Benichia480ba52018-09-03 08:19:02 +09003478 /**
3479 * Return an array of all current NetworkAgentInfos sorted by network id.
3480 */
3481 private NetworkAgentInfo[] networksSortedById() {
3482 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003483 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003484 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003485 return networks;
3486 }
3487
3488 /**
3489 * Return an array of all current NetworkRequest sorted by request id.
3490 */
James Mattis258ea3c2020-11-15 15:04:40 -08003491 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003492 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003493 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003494 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003495 // Sort the array based off the NRI containing the min requestId in its requests.
3496 Arrays.sort(requests,
3497 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3498 Comparator.comparingInt(req -> req.requestId)).requestId
3499 )
3500 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003501 return requests;
3502 }
3503
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003504 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003505 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003506 if (officialNai != null && officialNai.equals(nai)) return true;
3507 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003508 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003509 " - " + nai);
3510 }
3511 return false;
3512 }
3513
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003514 private boolean isDisconnectRequest(Message msg) {
3515 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3516 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3517 return info.getState() == NetworkInfo.State.DISCONNECTED;
3518 }
3519
Robert Greenwalt2034b912009-08-12 16:08:25 -07003520 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003521 private class NetworkStateTrackerHandler extends Handler {
3522 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003523 super(looper);
3524 }
3525
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003526 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003527 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3528 final NetworkAgentInfo nai = arg.first;
3529 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003530 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003531 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003532 }
3533 return;
3534 }
3535
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003536 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003537 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003538 return;
3539 }
3540
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003541 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003542 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003543 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3544 final NetworkCapabilities sanitized =
3545 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003546 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003547 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003548 break;
3549 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003550 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003551 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003552 processLinkPropertiesFromAgent(nai, newLp);
3553 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003554 break;
3555 }
3556 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003557 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003558 updateNetworkInfo(nai, info);
3559 break;
3560 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003561 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003562 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003563 break;
3564 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003565 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003566 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003567 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003568 // Note that if the NAI had been connected, this would affect the
3569 // score, and therefore would require re-mixing the score and performing
3570 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003571 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003572 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3573 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003574 // Mark the network as temporarily accepting partial connectivity so that it
3575 // will be validated (and possibly become default) even if it only provides
3576 // partial internet access. Note that if user connects to partial connectivity
3577 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3578 // out of wifi coverage) and if the same wifi is available again, the device
3579 // will auto connect to this wifi even though the wifi has "no internet".
3580 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003581 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003582 break;
3583 }
junyulai011b1f12019-01-03 18:50:15 +08003584 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003585 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003586 break;
3587 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003588 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003589 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003590 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003591
3592 if (isLegacyLockdownNai(nai)
3593 && (underlying == null || underlying.size() != 1)) {
3594 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3595 + " must have exactly one underlying network: " + underlying);
3596 }
3597
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003598 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3599 nai.declaredUnderlyingNetworks = (underlying != null)
3600 ? underlying.toArray(new Network[0]) : null;
3601
3602 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3603 if (DBG) {
3604 log(nai.toShortString() + " changed underlying networks to "
3605 + Arrays.toString(nai.declaredUnderlyingNetworks));
3606 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003607 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003608 notifyIfacesChangedForNetworkStats();
3609 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003610 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003611 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003612 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3613 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3614 nai.teardownDelayMs = msg.arg1;
3615 } else {
3616 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3617 }
Chalard Jean550b5212021-03-05 23:07:53 +09003618 break;
3619 }
3620 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3621 nai.setLingerDuration((int) arg.second);
3622 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003623 }
Tyler Wear72388212021-09-09 14:49:02 -07003624 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3625 DscpPolicy policy = (DscpPolicy) arg.second;
3626 if (mDscpPolicyTracker != null) {
3627 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3628 }
3629 break;
3630 }
3631 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3632 if (mDscpPolicyTracker != null) {
3633 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3634 }
3635 break;
3636 }
3637 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3638 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003639 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003640 }
3641 break;
3642 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003643 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003644 // If nai is not yet created, or is already destroyed, ignore.
3645 if (!shouldDestroyNativeNetwork(nai)) break;
3646
3647 final int timeoutMs = (int) arg.second;
3648 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3649 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3650 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3651 }
3652
3653 // Marking a network awaiting replacement is used to ensure that any requests
3654 // satisfied by the network do not switch to another network until a
3655 // replacement is available or the wait for a replacement times out.
3656 // If the network is inactive (i.e., nascent or lingering), then there are no
3657 // such requests, and there is no point keeping it. Just tear it down.
3658 // Note that setLingerDuration(0) cannot be used to do this because the network
3659 // could be nascent.
3660 nai.clearInactivityState();
3661 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3662 Log.d(TAG, nai.toShortString()
3663 + " marked awaiting replacement is unneeded, tearing down instead");
3664 teardownUnneededNetwork(nai);
3665 break;
3666 }
3667
3668 Log.d(TAG, "Marking " + nai.toShortString()
3669 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3670 destroyNativeNetwork(nai);
3671
3672 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3673 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3674 // consider the fact that the network could already have disconnected or been
3675 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3676 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3677 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3678 mKeepaliveTracker.handleStopAllKeepalives(nai,
3679 SocketKeepalive.ERROR_INVALID_NETWORK);
3680
3681 nai.updateScoreForNetworkAgentUpdate();
3682 // This rematch is almost certainly not going to result in any changes, because
3683 // the destroyed flag is only just above the "current satisfier wins"
3684 // tie-breaker. But technically anything that affects scoring should rematch.
3685 rematchAllNetworksAndRequests();
3686 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3687 break;
3688 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003689 }
3690 }
3691
3692 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003693 final int netId = msg.arg2;
3694 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003695 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003696 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003697 switch (msg.what) {
3698 default:
3699 return false;
lucasline117e2e2019-10-22 18:27:33 +08003700 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003701 if (nai == null) {
3702 break;
3703 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003704 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3705 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003706 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003707 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003708 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003709 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003710 if (probePrivateDnsCompleted) {
3711 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3712 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003713 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003714 }
3715 // Only show the notification when the private DNS is broken and the
3716 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003717 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003718 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3719 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003720 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003721 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3722 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3723 // private DNS is broken, it means this network is being reevaluated.
3724 // Either probing private DNS is not necessary any more or it hasn't been
3725 // done yet. In either case, the networkCapabilities should be updated to
3726 // reflect the new status.
3727 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003728 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003729 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003730 }
3731 break;
3732 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003733 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003734 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3735
Erik Kline31b4a9e2018-01-11 21:07:29 +09003736 if (nai == null) break;
3737
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003738 handleNetworkTested(nai, results.mTestResult,
3739 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003740 break;
3741 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003742 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003743 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003744 // If captive portal status has changed, update capabilities or disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003745 if (nai != null && (visible != nai.captivePortalDetected())) {
3746 nai.setCaptivePortalDetected(visible);
3747 if (visible && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
3748 == getCaptivePortalMode()) {
Chalard Jean49707572019-12-10 21:07:02 +09003749 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003750 nai.onPreventAutomaticReconnect();
Calvin Ondada1452016-10-11 15:10:46 -07003751 teardownUnneededNetwork(nai);
3752 break;
3753 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003754 updateCapabilitiesForNetwork(nai);
Paul Jensen53f08952015-06-16 14:27:36 -04003755 }
3756 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003757 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003758 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003759 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3760 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003761 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003762 if (nai == null) {
3763 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3764 break;
3765 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003766 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003767 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003768 (PendingIntent) msg.obj,
3769 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003770 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003771 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003772 break;
3773 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003774 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003775 if (nai == null) break;
3776
Erik Kline9a62f012018-03-21 07:18:33 -07003777 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003778 break;
3779 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003780 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003781 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003782 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003783 break;
3784 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003785 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003786 return true;
3787 }
3788
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003789 private void handleNetworkTested(
3790 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09003791 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
3792 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
3793 final boolean captive = !TextUtils.isEmpty(redirectUrl);
3794
3795 // If there is any kind of working networking, then the NAI has been evaluated
3796 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
3797 // the first time this ever happened.
3798 final boolean someConnectivity = (valid || partial || captive);
3799 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
3800 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
3801
he_won.hwang881307a2022-03-15 21:23:52 +09003802 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3803 // Assume the validation failure is due to a temporary failure after roaming
3804 // and ignore it. NetworkMonitor will continue to retry validation. If it
3805 // continues to fail after the block timeout expires, the network will be
3806 // marked unvalidated. If it succeeds, then validation state will not change.
3807 return;
3808 }
3809
Chalard Jean254bd162022-08-25 13:04:51 +09003810 final boolean wasValidated = nai.isValidated();
3811 final boolean wasPartial = nai.partialConnectivity();
3812 nai.setPartialConnectivity((testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0);
3813 final boolean partialConnectivityChanged = (wasPartial != nai.partialConnectivity());
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003814
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003815 if (DBG) {
3816 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3817 ? " with redirect to " + redirectUrl
3818 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003819 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003820 }
Chalard Jean254bd162022-08-25 13:04:51 +09003821 if (valid != nai.isValidated()) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003822 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09003823 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003824 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003825 if (valid) {
3826 handleFreshlyValidatedNetwork(nai);
3827 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
3828 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08003829 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003830 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003831 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003832 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003833 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003834 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003835 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003836 NotificationType.PRIVATE_DNS_BROKEN);
3837 // If network becomes valid, the hasShownBroken should be reset for
3838 // that network so that the notification will be fired when the private
3839 // DNS is broken again.
3840 nai.networkAgentConfig.hasShownBroken = false;
3841 }
3842 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003843 updateCapabilitiesForNetwork(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003844 } else if (becameEvaluated) {
3845 // If valid or partial connectivity changed, updateCapabilities* has
3846 // done the rematch.
3847 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003848 }
3849 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003850
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003851 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003852 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003853 nai.onValidationStatusChanged(
3854 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
3855 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003856
3857 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09003858 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003859 // immediately. Re-notify partial connectivity silently if no internet
3860 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09003861 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003862 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003863 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
3864 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003865 }
3866
Chalard Jean254bd162022-08-25 13:04:51 +09003867 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003868 handleNetworkUnvalidated(nai);
3869 }
3870 }
3871
Calvin Ondada1452016-10-11 15:10:46 -07003872 private int getCaptivePortalMode() {
3873 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08003874 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
3875 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07003876 }
3877
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003878 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
3879 switch (msg.what) {
3880 default:
3881 return false;
3882 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
3883 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
3884 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
3885 handleLingerComplete(nai);
3886 }
3887 break;
3888 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003889 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
3890 handleNetworkAgentRegistered(msg);
3891 break;
3892 }
3893 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
3894 handleNetworkAgentDisconnected(msg);
3895 break;
3896 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09003897 }
3898 return true;
3899 }
3900
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003901 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09003902 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08003903 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09003904 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003905 maybeHandleNetworkAgentMessage(msg);
3906 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003907 }
3908 }
3909
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003910 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09003911 private final int mNetId;
3912 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003913
3914 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08003915 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003916 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003917 }
3918
3919 @Override
3920 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
3921 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09003922 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003923 }
3924
3925 @Override
3926 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003927 // Legacy version of notifyNetworkTestedWithExtras.
3928 // Would only be called if the system has a NetworkStack module older than the
3929 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08003930 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003931 }
3932
3933 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003934 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09003935 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
3936 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003937 final Message msg = mTrackerHandler.obtainMessage(
3938 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003939 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003940 new NetworkTestedResults(
3941 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003942 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003943
3944 // Invoke ConnectivityReport generation for this Network test event.
3945 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
3946 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003947
Cody Kestingf1120be2020-08-03 18:01:40 -07003948 // NetworkMonitor reports the network validation result as a bitmask while
3949 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
3950 // logical value for ConnectivityDiagnostics.
3951 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
3952 p.result);
3953
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003954 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07003955 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003956 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
3957 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
3958
Aaron Huang959d3642021-01-21 15:47:41 +08003959 ConnectivityReportEvent reportEvent =
3960 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
3961 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09003962 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09003963 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003964 }
3965
3966 @Override
3967 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
3968 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3969 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09003970 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003971 }
3972
3973 @Override
lucasline117e2e2019-10-22 18:27:33 +08003974 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
3975 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3976 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003977 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08003978 }
3979
3980 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003981 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
3982 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
3983 EVENT_CAPPORT_DATA_CHANGED,
3984 0, mNetId, data));
3985 }
3986
3987 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003988 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003989 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09003990 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003991
3992 final PendingIntent pendingIntent;
3993 // Only the system server can register notifications with package "android"
3994 final long token = Binder.clearCallingIdentity();
3995 try {
paulhu7746e4e2020-06-09 19:07:03 +08003996 pendingIntent = PendingIntent.getBroadcast(
3997 mContext,
3998 0 /* requestCode */,
3999 intent,
4000 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004001 } finally {
4002 Binder.restoreCallingIdentity(token);
4003 }
4004 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4005 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004006 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004007 }
4008
4009 @Override
4010 public void hideProvisioningNotification() {
4011 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004012 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004013 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004014
4015 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004016 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004017 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004018 }
4019
4020 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004021 public int getInterfaceVersion() {
4022 return this.VERSION;
4023 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004024
4025 @Override
4026 public String getInterfaceHash() {
4027 return this.HASH;
4028 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004029 }
4030
Cody Kestingf1120be2020-08-03 18:01:40 -07004031 /**
4032 * Converts the given NetworkMonitor-specific validation result bitmask to a
4033 * ConnectivityDiagnostics-specific validation result int.
4034 */
4035 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4036 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4037 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4038 }
4039 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4040 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4041 }
4042 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4043 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4044 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4045 }
4046
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004047 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004048 log("Data stall detected with methods: " + p.detectionMethod);
4049
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004050 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004051 int detectionMethod = 0;
4052 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4053 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4054 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4055 }
4056 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4057 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4058 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4059 p.tcpMetricsCollectionPeriodMillis);
4060 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004061 }
4062
Cody Kestingf53a0752020-04-15 12:33:28 -07004063 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004064 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004065 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004066
4067 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4068 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4069 // the cost of going through two handlers.
4070 mConnectivityDiagnosticsHandler.sendMessage(msg);
4071 }
4072
Cody Kestingb37958e2020-05-15 10:36:01 -07004073 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4074 return (p.detectionMethod & detectionMethod) != 0;
4075 }
4076
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004077 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4078 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004079 }
4080
Erik Klinea73af002018-06-26 18:53:43 +09004081 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4082 if (nai == null) return;
4083 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4084 // in order to restart a validation pass from within netd.
4085 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4086 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004087 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004088 }
4089 }
4090
Erik Kline31b4a9e2018-01-11 21:07:29 +09004091 private void handlePrivateDnsSettingsChanged() {
4092 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4093
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004094 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004095 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004096 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004097 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4098 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004099 }
4100 }
4101
Erik Kline9a62f012018-03-21 07:18:33 -07004102 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4103 // Private DNS only ever applies to networks that might provide
4104 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004105 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004106
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004107 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004108 // schedule DNS resolutions. If a DNS resolution is required the
4109 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004110 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004111
4112 // With Private DNS bypass support, we can proceed to update the
4113 // Private DNS config immediately, even if we're in strict mode
4114 // and have not yet resolved the provider name into a set of IPs.
4115 updatePrivateDns(nai, cfg);
4116 }
4117
4118 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4119 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004120 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004121 }
4122
dalyk1720e542018-03-05 12:42:22 -05004123 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4124 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4125 if (nai == null) {
4126 return;
4127 }
4128 mDnsManager.updatePrivateDnsValidation(update);
4129 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4130 }
4131
paulhu7c0a2e62021-01-08 00:51:49 +08004132 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004133 int prefixLength) {
4134 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4135 if (nai == null) return;
4136
paulhu7c0a2e62021-01-08 00:51:49 +08004137 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4138 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004139
4140 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004141 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004142 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004143 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004144 prefixLength);
4145 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004146 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004147 return;
4148 }
4149 }
4150
Lorenzo Colittid523d142020-04-01 20:16:30 +09004151 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004152 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4153 }
4154
Hai Shalome58bdc62021-01-11 18:45:34 -08004155 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004156 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004157 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004158 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4159 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4160 }
4161
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004162 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004163 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004164 * @param nai the agent info to update
4165 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004166 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004167 */
junyulai2b6f0c22021-02-03 20:15:30 +08004168 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4169 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4170 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004171 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004172 // one lingered request, set inactive.
4173 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004174 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004175 if (DBG) log("Unsetting inactive " + nai.toShortString());
4176 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004177 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004178 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004179 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004180 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4181 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004182 }
junyulai2b6f0c22021-02-03 20:15:30 +08004183 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004184 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004185 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004186 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004187 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004188 }
4189
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004190 private void handleNetworkAgentRegistered(Message msg) {
4191 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4192 if (!mNetworkAgentInfos.contains(nai)) {
4193 return;
4194 }
4195
4196 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4197 if (VDBG) log("NetworkAgent registered");
4198 } else {
4199 loge("Error connecting NetworkAgent");
4200 mNetworkAgentInfos.remove(nai);
4201 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004202 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004203 synchronized (mNetworkForNetId) {
4204 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004205 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004206 mNetIdManager.releaseNetId(nai.network.getNetId());
4207 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004208 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004209 }
4210 }
4211 }
Paul Jensend5f53392014-11-25 15:26:53 -05004212
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004213 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004214 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004215 }
4216
he_won.hwang881307a2022-03-15 21:23:52 +09004217 private boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004218 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004219 if (SdkLevel.isAtLeastT()) return false;
4220 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4221 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
4222 if (blockTimeOut <= MAX_VALIDATION_FAILURE_BLOCKING_TIME_MS
4223 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004224 final long currentTimeMs = SystemClock.elapsedRealtime();
4225 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004226 if (timeSinceLastRoam <= blockTimeOut) {
4227 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4228 return true;
4229 }
4230 }
4231 return false;
4232 }
4233
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004234 private void handleNetworkAgentDisconnected(Message msg) {
4235 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004236 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004237 }
4238
Chalard Jeand9fffc32018-05-11 20:19:20 +09004239 // Destroys a network, remove references to it from the internal state managed by
4240 // ConnectivityService, free its interfaces and clean up.
4241 // Must be called on the Handler thread.
4242 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004243 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004244
4245 if (!mNetworkAgentInfos.contains(nai)) return;
4246
Chalard Jeand9fffc32018-05-11 20:19:20 +09004247 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004248 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004249 }
lucaslinb25c9a62019-02-12 15:30:13 +08004250 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004251 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004252 // A network agent has disconnected.
4253 // TODO - if we move the logic to the network agent (have them disconnect
4254 // because they lost all their requests or because their score isn't good)
4255 // then they would disconnect organically, report their new state and then
4256 // disconnect the channel.
4257 if (nai.networkInfo.isConnected()) {
4258 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4259 null, null);
4260 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004261 final boolean wasDefault = isDefaultNetwork(nai);
4262 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004263 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004264 }
4265 notifyIfacesChangedForNetworkStats();
4266 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4267 // by other networks that are already connected. Perhaps that can be done by
4268 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4269 // of rematchAllNetworksAndRequests
4270 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004271 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004272
4273 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004274 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4275 // Disable wakeup packet monitoring for each interface.
4276 wakeupModifyInterface(iface, nai.networkCapabilities, false);
4277 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004278 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004279 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004280 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004281 synchronized (mNetworkForNetId) {
4282 // Remove the NetworkAgent, but don't mark the netId as
4283 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004284 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004285 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004286 propagateUnderlyingNetworkCapabilities(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004287 // Remove all previously satisfied requests.
4288 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004289 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004290 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004291 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004292 if (currentNetwork != null
4293 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004294 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004295 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4296 // rematch not to keep disconnected agents instead of setting it here ; this
4297 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004298 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004299 for (final NetworkOfferInfo noi : mNetworkOffers) {
4300 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004301 }
James Mattise3ef1912020-12-20 11:09:58 -08004302
Chalard Jean5b409c72021-02-04 13:12:59 +09004303 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004304 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004305 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004306 // network, because while incorrect this is the closest to the old (also
4307 // incorrect) behavior.
4308 mNetworkActivityTracker.updateDataActivityTracking(
4309 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004310 ensureNetworkTransitionWakelock(nai.toShortString());
4311 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004312 }
4313 }
junyulai2b6f0c22021-02-03 20:15:30 +08004314 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004315 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004316 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004317 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004318 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004319 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004320 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004321
4322 // Immediate teardown.
4323 if (nai.teardownDelayMs == 0) {
4324 destroyNetwork(nai);
4325 return;
4326 }
4327
4328 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004329 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304330 try {
4331 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4332 } catch (RemoteException e) {
4333 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4334 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004335 }
4336 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4337 }
4338
4339 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004340 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004341 // Tell netd to clean up the configuration for this network
4342 // (routing rules, DNS, etc).
4343 // This may be slow as it requires a lot of netd shelling out to ip and
4344 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004345 // after we've rematched networks with requests (which might change the default
4346 // network or service a new request from an app), so network traffic isn't interrupted
4347 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004348 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004349 }
Chalard Jean254bd162022-08-25 13:04:51 +09004350 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004351 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4352 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4353 // false if the network was never created.
4354 // TODO: delete when S is no longer supported.
4355 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004356 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004357 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004358 }
4359
Ken Chen6df7a902021-04-09 15:08:42 +08004360 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004361 try {
4362 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004363 final NativeNetworkConfig config;
4364 if (nai.isVPN()) {
4365 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004366 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004367 return false;
4368 }
4369 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4370 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004371 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004372 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004373 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004374 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004375 getNetworkPermission(nai.networkCapabilities),
4376 false /* secure */,
4377 VpnManager.TYPE_VPN_NONE,
4378 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004379 }
Ken Chen6df7a902021-04-09 15:08:42 +08004380 mNetd.networkCreate(config);
4381 mDnsResolver.createNetworkCache(nai.network.getNetId());
4382 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4383 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004384 return true;
4385 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004386 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004387 return false;
4388 }
4389 }
4390
Ken Chen6df7a902021-04-09 15:08:42 +08004391 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004392 if (mDscpPolicyTracker != null) {
4393 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4394 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004395 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004396 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004397 } catch (RemoteException | ServiceSpecificException e) {
4398 loge("Exception destroying network(networkDestroy): " + e);
4399 }
4400 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004401 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004402 } catch (RemoteException | ServiceSpecificException e) {
4403 loge("Exception destroying network: " + e);
4404 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004405 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4406 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4407 // gets created, could add data to DnsManager data structures that will never get deleted.
4408 mDnsManager.removeNetwork(nai.network);
4409
4410 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004411 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004412 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4413 }
4414
Chalard Jean254bd162022-08-25 13:04:51 +09004415 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004416 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004417 }
4418
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004419 // If this method proves to be too slow then we can maintain a separate
4420 // pendingIntent => NetworkRequestInfo map.
4421 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4422 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004423 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4424 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4425 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004426 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004427 return entry.getValue();
4428 }
4429 }
4430 return null;
4431 }
4432
Chalard Jean524f0b12021-10-25 21:11:56 +09004433 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4434 if (SdkLevel.isAtLeastT()) {
4435 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4436 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4437 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4438 // bug is fixed.
4439 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004440 throw new IllegalStateException("This NRI is already registered. New : " + nri
4441 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004442 }
4443 }
4444 }
4445 }
4446
Chalard Jeanac9ace02022-01-26 16:54:05 +09004447 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4448 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004449 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004450 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4451 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004452 }
4453 return false;
4454 }
4455
James Mattisf7027322020-12-13 16:28:14 -08004456 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004457 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004458 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4459 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4460 final NetworkRequestInfo existingRequest =
4461 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004462 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004463 if (DBG) {
4464 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4465 + nri.mRequests.get(0) + " because their intents matched.");
4466 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004467 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004468 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004469 }
Erik Kline05f2b402015-04-30 12:58:40 +09004470 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004471 }
4472
James Mattisf7027322020-12-13 16:28:14 -08004473 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004474 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004475 }
4476
James Mattis3ce3d3c2021-02-09 18:18:28 -08004477 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004478 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004479 for (final NetworkRequestInfo nri : nris) {
4480 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004481 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004482 for (final NetworkRequest req : nri.mRequests) {
4483 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004484 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004485 if (req.isListen()) {
4486 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4487 if (req.networkCapabilities.hasSignalStrength()
4488 && network.satisfiesImmutableCapabilitiesOf(req)) {
4489 updateSignalStrengthThresholds(network, "REGISTER", req);
4490 }
James Mattisf7027322020-12-13 16:28:14 -08004491 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004492 }
4493 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004494
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004495 // If this NRI has a satisfier already, it is replacing an older request that
4496 // has been removed. Track it.
4497 final NetworkRequest activeRequest = nri.getActiveRequest();
4498 if (null != activeRequest) {
4499 // If there is an active request, then for sure there is a satisfier.
4500 nri.getSatisfier().addRequest(activeRequest);
4501 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004502 }
James Mattisf7027322020-12-13 16:28:14 -08004503
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004504 if (mFlags.noRematchAllRequestsOnRegister()) {
4505 rematchNetworksAndRequests(nris);
4506 } else {
4507 rematchAllNetworksAndRequests();
4508 }
James Mattis45d81842021-01-10 14:24:24 -08004509
Chalard Jean0354d8c2021-01-12 10:58:56 +09004510 // Requests that have not been matched to a network will not have been sent to the
4511 // providers, because the old satisfier and the new satisfier are the same (null in this
4512 // case). Send these requests to the providers.
4513 for (final NetworkRequestInfo nri : nris) {
4514 for (final NetworkOfferInfo noi : mNetworkOffers) {
4515 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004516 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004517 }
4518 }
4519
James Mattisf7027322020-12-13 16:28:14 -08004520 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4521 final int callingUid) {
4522 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004523 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004524 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4525 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4526 handleReleaseNetworkRequest(
4527 nri.mRequests.get(0),
4528 callingUid,
4529 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004530 }
4531 }
4532
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004533 // Determines whether the network is the best (or could become the best, if it validated), for
4534 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4535 // on the value of reason:
4536 //
4537 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4538 // then it should be torn down.
4539 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4540 // then it should be lingered.
4541 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004542 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004543
Chalard Jean254bd162022-08-25 13:04:51 +09004544 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004545 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4546 return false;
4547 }
4548
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004549 final int numRequests;
4550 switch (reason) {
4551 case TEARDOWN:
4552 numRequests = nai.numRequestNetworkRequests();
4553 break;
4554 case LINGER:
4555 numRequests = nai.numForegroundNetworkRequests();
4556 break;
4557 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004558 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004559 return true;
4560 }
4561
Chalard Jean947acd42021-03-08 22:29:27 +09004562 if (numRequests > 0) return false;
4563
Paul Jensende49eb12015-06-25 15:30:08 -04004564 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004565 if (reason == UnneededFor.LINGER
4566 && !nri.isMultilayerRequest()
4567 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004568 // Background requests don't affect lingering.
4569 continue;
4570 }
4571
James Mattis3d229892020-11-16 16:46:28 -08004572 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004573 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004574 }
4575 }
Paul Jensende49eb12015-06-25 15:30:08 -04004576 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004577 }
4578
James Mattis3d229892020-11-16 16:46:28 -08004579 private boolean isNetworkPotentialSatisfier(
4580 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4581 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004582 // request, return immediately. For multilayer requests, check to see if any of the
4583 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004584 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4585 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004586 return false;
4587 }
4588 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004589 // This multilayer listen request is satisfied therefore no further requests need to be
4590 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004591 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004592 return false;
4593 }
James Mattis3d229892020-11-16 16:46:28 -08004594 // As non-multilayer listen requests have already returned, the below would only happen
4595 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004596 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004597 continue;
4598 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004599 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004600 // there is hope for it to become one if it validated, then it is needed.
4601 if (candidate.satisfies(req)) {
4602 // As soon as a network is found that satisfies a request, return. Specifically for
4603 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4604 // is important so as to not evaluate lower priority requests further in
4605 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004606 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4607 ? nri.getSatisfier() : null;
4608 // Note that this catches two important cases:
4609 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4610 // is currently satisfying the request. This is desirable when
4611 // cellular ends up validating but WiFi does not.
4612 // 2. Unvalidated WiFi will not be reaped when validated cellular
4613 // is currently satisfying the request. This is desirable when
4614 // WiFi ends up validating and out scoring cellular.
4615 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004616 }
4617 }
4618
4619 return false;
4620 }
4621
Erik Kline0c04b742016-07-07 16:50:58 +09004622 private NetworkRequestInfo getNriForAppRequest(
4623 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004624 // Looking up the app passed param request in mRequests isn't possible since it may return
4625 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4626 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004627 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4628 // to avoid potential race conditions when validating a package->uid mapping when sending
4629 // the callback on the very low-chance that an application shuts down prior to the callback
4630 // being sent.
4631 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4632 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004633
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004634 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004635 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004636 log(String.format("UID %d attempted to %s for unowned request %s",
4637 callingUid, requestedOperation, nri));
4638 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004639 }
Erik Kline0c04b742016-07-07 16:50:58 +09004640 }
4641
4642 return nri;
4643 }
4644
James Mattisf7027322020-12-13 16:28:14 -08004645 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4646 final String callingMethod) {
4647 if (nri.isMultilayerRequest()) {
4648 throw new IllegalStateException(
4649 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004650 }
4651 }
4652
James Mattisf7027322020-12-13 16:28:14 -08004653 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004654 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004655 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4656 // single NetworkRequest and thus does not apply to multilayer requests.
4657 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4658 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004659 return;
4660 }
James Mattis2516da32021-01-31 17:06:19 -08004661 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004662 return;
4663 }
James Mattisf7027322020-12-13 16:28:14 -08004664 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4665 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004666 }
4667 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004668 callCallbackForRequest(
4669 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004670 }
4671
James Mattisf7027322020-12-13 16:28:14 -08004672 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4673 final int callingUid,
4674 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004675 final NetworkRequestInfo nri =
4676 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4677 if (nri == null) {
4678 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004679 }
James Mattisf7027322020-12-13 16:28:14 -08004680 if (VDBG || (DBG && request.isRequest())) {
4681 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004682 }
4683 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004684 if (callOnUnavailable) {
4685 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4686 }
Erik Kline155a59a2015-11-25 12:49:38 +09004687 }
Erik Kline0c04b742016-07-07 16:50:58 +09004688
James Mattisa076c532020-12-02 14:12:41 -08004689 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004690 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004691 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004692 if (null == mNetworkRequests.remove(req)) {
4693 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4694 continue;
4695 }
James Mattisa076c532020-12-02 14:12:41 -08004696 if (req.isListen()) {
4697 removeListenRequestFromNetworks(req);
4698 }
4699 }
James Mattis8f036802021-06-20 16:26:01 -07004700 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004701 if (mDefaultNetworkRequests.remove(nri)) {
4702 // If this request was one of the defaults, then the UID rules need to be updated
4703 // WARNING : if the app(s) for which this network request is the default are doing
4704 // traffic, this will kill their connected sockets, even if an equivalent request
4705 // is going to be reinstated right away ; unconnected traffic will go on the default
4706 // until the new default is set, which will happen very soon.
4707 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4708 // remove ranges for those requests that won't have a replacement
4709 final NetworkAgentInfo satisfier = nri.getSatisfier();
4710 if (null != satisfier) {
4711 try {
paulhu0e79d952021-06-09 16:11:35 +08004712 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4713 satisfier.network.getNetId(),
4714 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004715 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004716 } catch (RemoteException e) {
4717 loge("Exception setting network preference default network", e);
4718 }
4719 }
4720 }
Junyu Lai00d92df2022-07-05 11:01:52 +08004721 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004722 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004723 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004724
4725 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004726 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004727 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004728 }
4729 }
4730
Chalard Jean0354d8c2021-01-12 10:58:56 +09004731 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4732 // needed for this offer.
4733 for (final NetworkOfferInfo noi : mNetworkOffers) {
4734 for (final NetworkRequest req : nri.mRequests) {
4735 if (req.isRequest() && noi.offer.neededFor(req)) {
4736 noi.offer.onNetworkUnneeded(req);
4737 }
4738 }
4739 }
James Mattisa076c532020-12-02 14:12:41 -08004740 }
4741
James Mattis3ce3d3c2021-02-09 18:18:28 -08004742 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4743 for (final NetworkRequestInfo nri : nris) {
4744 if (mDefaultRequest == nri) {
4745 // Make sure we never remove the default request.
4746 continue;
4747 }
4748 handleRemoveNetworkRequest(nri);
4749 }
4750 }
4751
James Mattisa076c532020-12-02 14:12:41 -08004752 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4753 // listens don't have a singular affected Network. Check all networks to see
4754 // if this listen request applies and remove it.
4755 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4756 nai.removeRequest(req.requestId);
4757 if (req.networkCapabilities.hasSignalStrength()
4758 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4759 updateSignalStrengthThresholds(nai, "RELEASE", req);
4760 }
4761 }
4762 }
4763
4764 /**
4765 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4766 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4767 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4768 */
4769 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4770 boolean wasKept = false;
4771 final NetworkAgentInfo nai = nri.getSatisfier();
4772 if (nai != null) {
4773 final int requestLegacyType = nri.getActiveRequest().legacyType;
4774 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4775 nai.removeRequest(nri.getActiveRequest().requestId);
4776 if (VDBG || DDBG) {
4777 log(" Removing from current network " + nai.toShortString()
4778 + ", leaving " + nai.numNetworkRequests() + " requests.");
4779 }
4780 // If there are still lingered requests on this network, don't tear it down,
4781 // but resume lingering instead.
4782 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004783 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004784 notifyNetworkLosing(nai, now);
4785 }
4786 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4787 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4788 teardownUnneededNetwork(nai);
4789 } else {
4790 wasKept = true;
4791 }
James Mattisa076c532020-12-02 14:12:41 -08004792 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4793 // Went from foreground to background.
4794 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004795 }
4796
Erik Kline0c04b742016-07-07 16:50:58 +09004797 // Maintain the illusion. When this request arrived, we might have pretended
4798 // that a network connected to serve it, even though the network was already
4799 // connected. Now that this request has gone away, we might have to pretend
4800 // that the network disconnected. LegacyTypeTracker will generate that
4801 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08004802 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09004803 boolean doRemove = true;
4804 if (wasKept) {
4805 // check if any of the remaining requests for this network are for the
4806 // same legacy type - if so, don't remove the nai
4807 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4808 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08004809 if (otherRequest.legacyType == requestLegacyType
4810 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004811 if (DBG) log(" still have other legacy request - leaving");
4812 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08004813 }
4814 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07004815 }
4816
Erik Kline0c04b742016-07-07 16:50:58 +09004817 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08004818 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09004819 }
4820 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004821 }
4822 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004823
Junyu Lai00d92df2022-07-05 11:01:52 +08004824 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09004825 return checkAnyPermissionOf(
4826 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4827 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
4828 }
4829
Lorenzo Colittid6459092016-07-04 12:55:44 +09004830 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004831 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08004832 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004833 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09004834 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004835 }
4836
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004837 @Override
lucaslin2240ef62019-03-12 13:08:03 +08004838 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
4839 enforceNetworkStackSettingsOrSetup();
4840 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
4841 encodeBool(accept), encodeBool(always), network));
4842 }
4843
4844 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004845 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08004846 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004847 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
4848 }
4849
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08004850 @Override
4851 public void setTestAllowBadWifiUntil(long timeMs) {
4852 enforceSettingsPermission();
4853 if (!Build.isDebuggable()) {
4854 throw new IllegalStateException("Does not support in non-debuggable build");
4855 }
4856
4857 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
4858 throw new IllegalArgumentException("It should not exceed "
4859 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
4860 }
4861
4862 mHandler.sendMessage(
4863 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
4864 }
4865
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004866 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
4867 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
4868 " accept=" + accept + " always=" + always);
4869
4870 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4871 if (nai == null) {
4872 // Nothing to do.
4873 return;
4874 }
4875
Chalard Jean254bd162022-08-25 13:04:51 +09004876 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004877 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004878 return;
4879 }
4880
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004881 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08004882 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004883 }
4884
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004885 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
4886 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004887 // If network becomes partial connectivity and user already accepted to use this
4888 // network, we should respect the user's option and don't need to popup the
4889 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004890 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09004891 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004892 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004893 }
4894
4895 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004896 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004897 }
4898
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004899 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04004900 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004901 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09004902 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04004903 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09004904 }
4905
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004906 }
4907
lucaslin2240ef62019-03-12 13:08:03 +08004908 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
4909 boolean always) {
4910 if (DBG) {
4911 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
4912 + " always=" + always);
4913 }
4914
4915 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4916 if (nai == null) {
4917 // Nothing to do.
4918 return;
4919 }
4920
Chalard Jean254bd162022-08-25 13:04:51 +09004921 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08004922 // The network validated while the dialog box was up. Take no action.
4923 return;
4924 }
4925
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004926 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
4927 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08004928 }
4929
4930 // TODO: Use the current design or save the user choice into IpMemoryStore.
4931 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004932 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08004933 }
4934
4935 if (!accept) {
4936 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004937 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08004938 // Tear down the network.
4939 teardownUnneededNetwork(nai);
4940 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08004941 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
4942 // result in a partial connectivity result which will be processed by
4943 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08004944 //
4945 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
4946 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004947 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08004948 }
4949 }
4950
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004951 private void handleSetAvoidUnvalidated(Network network) {
4952 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09004953 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004954 // Nothing to do. The network either disconnected or revalidated.
4955 return;
4956 }
Chalard Jean254bd162022-08-25 13:04:51 +09004957 if (0L == nai.getAvoidUnvalidated()) {
4958 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09004959 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004960 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09004961 }
4962 }
4963
Chalard Jean5fb43c72022-09-08 19:03:14 +09004964 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09004965 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09004966 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004967 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09004968 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09004969 }
4970
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004971 @Override
4972 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08004973 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004974 mHandler.post(() -> {
4975 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
4976 if (nai == null) return;
4977 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004978 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09004979 });
4980 }
4981
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004982 /**
4983 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
4984 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004985 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004986 * @param appExtras Bundle to use as intent extras for the captive portal application.
4987 * Must be treated as opaque to avoid preventing the captive portal app to
4988 * update its arguments.
4989 */
4990 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004991 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08004992 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
4993 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004994
4995 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
4996 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09004997 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
4998 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09004999 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5000
lucaslin75ff7022020-12-17 04:14:35 +08005001 final long token = Binder.clearCallingIdentity();
5002 try {
5003 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5004 } finally {
5005 Binder.restoreCallingIdentity(token);
5006 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005007 }
5008
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005009 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5010 private final Network mNetwork;
5011
5012 private CaptivePortalImpl(Network network) {
5013 mNetwork = network;
5014 }
5015
5016 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005017 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005018 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5019 enforceSettingsPermission();
5020 }
5021
Chiachang Wang938bfba2020-01-09 13:50:55 +08005022 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005023 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005024 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005025 }
5026
5027 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005028 public void appRequest(final int request) {
5029 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5030 if (nm == null) return;
5031
5032 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005033 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005034 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005035 }
5036 }
5037
5038 @Nullable
5039 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5040 // getNetworkAgentInfoForNetwork is thread-safe
5041 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5042 if (nai == null) return null;
5043
5044 // nai.networkMonitor() is thread-safe
5045 return nai.networkMonitor();
5046 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005047 }
5048
Hugo Benichic9048bc2016-09-14 23:23:08 +00005049 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005050 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005051 }
5052
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005053 /**
5054 * Return whether the device should maintain continuous, working connectivity by switching away
5055 * from WiFi networks having no connectivity.
5056 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5057 */
5058 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005059 if (!checkNetworkStackPermission()) {
5060 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5061 }
5062 return avoidBadWifi();
5063 }
5064
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005065 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005066 ensureRunningOnConnectivityServiceThread();
5067 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005068 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005069 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005070 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005071 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5072 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5073 for (final NetworkOfferInfo noi : offersToUpdate) {
5074 updateOfferScore(noi.offer);
5075 }
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005076 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005077 }
5078
Erik Kline95ecfee2016-10-02 18:02:14 +09005079 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005080 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005081 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005082 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005083 if (!configRestrict) {
5084 pw.println("Bad Wi-Fi avoidance: unrestricted");
5085 return;
5086 }
5087
5088 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5089 pw.increaseIndent();
5090 pw.println("Config restrict: " + configRestrict);
5091
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005092 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005093 String description;
5094 // Can't use a switch statement because strings are legal case labels, but null is not.
5095 if ("0".equals(value)) {
5096 description = "get stuck";
5097 } else if (value == null) {
5098 description = "prompt";
5099 } else if ("1".equals(value)) {
5100 description = "avoid";
5101 } else {
5102 description = value + " (?)";
5103 }
5104 pw.println("User setting: " + description);
5105 pw.println("Network overrides:");
5106 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005107 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005108 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005109 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005110 }
5111 }
5112 pw.decreaseIndent();
5113 pw.decreaseIndent();
5114 }
5115
paulhu7746e4e2020-06-09 19:07:03 +08005116 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5117 // unify the method.
5118 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5119 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5120 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5121 return settingsComponent != null
5122 ? settingsComponent.getPackageName() : "com.android.settings";
5123 }
5124
lucaslinb1e8e382019-01-24 15:55:30 +08005125 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005126 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005127 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005128 switch (type) {
5129 case NO_INTERNET:
5130 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005131 // High priority because it is only displayed for explicitly selected networks.
5132 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005133 break;
lucasline117e2e2019-10-22 18:27:33 +08005134 case PRIVATE_DNS_BROKEN:
5135 action = Settings.ACTION_WIRELESS_SETTINGS;
5136 // High priority because we should let user know why there is no internet.
5137 highPriority = true;
5138 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005139 case LOST_INTERNET:
5140 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005141 // High priority because it could help the user avoid unexpected data usage.
5142 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005143 break;
lucaslin2240ef62019-03-12 13:08:03 +08005144 case PARTIAL_CONNECTIVITY:
5145 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005146 // Don't bother the user with a high-priority notification if the network was not
5147 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005148 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005149 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005150 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005151 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005152 return;
5153 }
5154
5155 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005156 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005157 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005158 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005159 // Some OEMs have their own Settings package. Thus, need to get the current using
5160 // Settings package name instead of just use default name "com.android.settings".
5161 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5162 intent.setClassName(settingsPkgName,
5163 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005164 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005165
paulhu2af50222020-10-11 22:52:27 +08005166 PendingIntent pendingIntent = PendingIntent.getActivity(
5167 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005168 0 /* requestCode */,
5169 intent,
paulhu2af50222020-10-11 22:52:27 +08005170 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005171
Serik Beketayevec8ad212020-12-07 22:43:07 -08005172 mNotifier.showNotification(
5173 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005174 }
5175
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005176 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5177 // Don't prompt if the network is validated, and don't prompt on captive portals
5178 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005179 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005180 return false;
5181 }
5182
5183 // If a network has partial connectivity, always prompt unless the user has already accepted
5184 // partial connectivity and selected don't ask again. This ensures that if the device
5185 // automatically connects to a network that has partial Internet access, the user will
5186 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005187 // because we have prompted them.
5188 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005189 return true;
5190 }
5191
5192 // If a network has no Internet access, only prompt if the network was explicitly selected
5193 // and if the user has not already told us to use the network regardless of whether it
5194 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005195 if (nai.networkAgentConfig.explicitlySelected
5196 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005197 return true;
5198 }
5199
5200 return false;
5201 }
5202
Chalard Jean5fb43c72022-09-08 19:03:14 +09005203 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5204 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005205
Chalard Jean5fb43c72022-09-08 19:03:14 +09005206 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5207 if (null == nai) return;
5208
5209 if (nai.setEvaluated()) {
5210 // If setEvaluated() returned true, the network never had any form of connectivity.
5211 // This may have an impact on request matching if bad WiFi avoidance is off and the
5212 // network was found not to have Internet access.
5213 nai.updateScoreForNetworkAgentUpdate();
5214 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005215 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005216
Chalard Jean5fb43c72022-09-08 19:03:14 +09005217 if (!shouldPromptUnvalidated(nai)) return;
5218
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005219 // Stop automatically reconnecting to this network in the future. Automatically connecting
5220 // to a network that provides no or limited connectivity is not useful, because the user
5221 // cannot use that network except through the notification shown by this method, and the
5222 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005223 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005224
Chalard Jean254bd162022-08-25 13:04:51 +09005225 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005226 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005227 } else {
5228 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5229 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005230 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005231
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005232 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5233 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005234 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005235
lucaslin2240ef62019-03-12 13:08:03 +08005236 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5237 return;
5238 }
5239
5240 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005241 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005242 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005243 }
5244
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005245 @Override
5246 public int getMultipathPreference(Network network) {
5247 enforceAccessPermission();
5248
5249 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005250 if (nai != null && nai.networkCapabilities
5251 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005252 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5253 }
5254
Aaron Huang9a57acf2020-12-08 10:03:29 +08005255 final NetworkPolicyManager netPolicyManager =
5256 mContext.getSystemService(NetworkPolicyManager.class);
5257
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005258 final long token = Binder.clearCallingIdentity();
5259 final int networkPreference;
5260 try {
5261 networkPreference = netPolicyManager.getMultipathPreference(network);
5262 } finally {
5263 Binder.restoreCallingIdentity(token);
5264 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005265 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005266 return networkPreference;
5267 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005268 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5269 }
5270
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005271 @Override
5272 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005273 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005274 }
5275
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005276 private class InternalHandler extends Handler {
5277 public InternalHandler(Looper looper) {
5278 super(looper);
5279 }
5280
5281 @Override
5282 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005283 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005284 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005285 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005286 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005287 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005288 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005289 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005290 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005291 break;
5292 }
Jason Monka69f1b02013-10-10 14:02:51 -04005293 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005294 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5295 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005296 break;
5297 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005298 case EVENT_REGISTER_NETWORK_PROVIDER: {
5299 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005300 break;
5301 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005302 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5303 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005304 break;
5305 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005306 case EVENT_REGISTER_NETWORK_OFFER: {
5307 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5308 break;
5309 }
5310 case EVENT_UNREGISTER_NETWORK_OFFER: {
5311 final NetworkOfferInfo offer =
5312 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5313 if (null != offer) {
5314 handleUnregisterNetworkOffer(offer);
5315 }
5316 break;
5317 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005318 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005319 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5320 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5321 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005322 break;
5323 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005324 case EVENT_REGISTER_NETWORK_REQUEST:
5325 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005326 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005327 break;
5328 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005329 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5330 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005331 handleRegisterNetworkRequestWithIntent(msg);
5332 break;
5333 }
Erik Kline155a59a2015-11-25 12:49:38 +09005334 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5335 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5336 handleTimedOutNetworkRequest(nri);
5337 break;
5338 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005339 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5340 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5341 break;
5342 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005343 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005344 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5345 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005346 break;
5347 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005348 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005349 Network network = (Network) msg.obj;
5350 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005351 break;
5352 }
lucaslin2240ef62019-03-12 13:08:03 +08005353 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5354 Network network = (Network) msg.obj;
5355 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5356 toBool(msg.arg2));
5357 break;
5358 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005359 case EVENT_SET_AVOID_UNVALIDATED: {
5360 handleSetAvoidUnvalidated((Network) msg.obj);
5361 break;
5362 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005363 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5364 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005365 break;
5366 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005367 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5368 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005369 break;
5370 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005371 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005372 case NetworkAgent.CMD_START_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005373 mKeepaliveTracker.handleStartKeepalive(msg);
5374 break;
5375 }
5376 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005377 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005378 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5379 int slot = msg.arg1;
5380 int reason = msg.arg2;
5381 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
5382 break;
5383 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005384 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5385 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5386 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005387 break;
5388 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005389 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5390 handlePrivateDnsSettingsChanged();
5391 break;
dalyk1720e542018-03-05 12:42:22 -05005392 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5393 handlePrivateDnsValidationUpdate(
5394 (PrivateDnsValidationUpdate) msg.obj);
5395 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005396 case EVENT_UID_BLOCKED_REASON_CHANGED:
5397 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005398 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005399 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5400 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5401 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005402 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005403 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5404 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005405 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005406 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005407 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005408 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08005409 final Pair<List<ProfileNetworkPreferenceList.Preference>,
5410 IOnCompleteListener> arg =
5411 (Pair<List<ProfileNetworkPreferenceList.Preference>,
5412 IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005413 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005414 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005415 }
lucaslin1193a5d2021-01-21 02:04:15 +08005416 case EVENT_REPORT_NETWORK_ACTIVITY:
5417 mNetworkActivityTracker.handleReportNetworkActivity();
5418 break;
paulhu51f77dc2021-06-07 02:34:20 +00005419 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5420 handleMobileDataPreferredUidsChanged();
5421 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005422 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5423 final long timeMs = ((Long) msg.obj).longValue();
5424 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5425 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005426 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5427 handleIngressRateLimitChanged();
5428 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08005429 }
5430 }
5431 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005432
Lorenzo Colittid6459092016-07-04 12:55:44 +09005433 @Override
markchien5776f962019-12-16 20:15:20 +08005434 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005435 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005436 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005437 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5438 Context.TETHERING_SERVICE);
5439 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005440 }
5441
Lorenzo Colittid6459092016-07-04 12:55:44 +09005442 @Override
markchien5776f962019-12-16 20:15:20 +08005443 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005444 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005445 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005446 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5447 Context.TETHERING_SERVICE);
5448 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005449 }
5450
Lorenzo Colittid6459092016-07-04 12:55:44 +09005451 @Override
markchien5776f962019-12-16 20:15:20 +08005452 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005453 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005454 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005455 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5456 Context.TETHERING_SERVICE);
5457 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005458 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005459
markchien5776f962019-12-16 20:15:20 +08005460
Lorenzo Colittid6459092016-07-04 12:55:44 +09005461 @Override
markchien5776f962019-12-16 20:15:20 +08005462 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005463 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005464 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005465 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5466 Context.TETHERING_SERVICE);
5467
5468 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005469 }
5470
Lorenzo Colittid6459092016-07-04 12:55:44 +09005471 @Override
markchien5776f962019-12-16 20:15:20 +08005472 @Deprecated
5473 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005474 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005475 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5476 Context.TETHERING_SERVICE);
5477
5478 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005479 }
5480
Udam Saini8f7d6a72017-06-07 12:06:28 -07005481 @Override
markchien5776f962019-12-16 20:15:20 +08005482 @Deprecated
5483 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005484 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005485 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5486 Context.TETHERING_SERVICE);
5487 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005488 }
5489
Robert Greenwalte0b00512014-07-02 09:59:16 -07005490 // Called when we lose the default network and have no replacement yet.
5491 // This will automatically be cleared after X seconds or a new default network
5492 // becomes CONNECTED, whichever happens first. The timer is started by the
5493 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005494 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005495 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005496 if (mNetTransitionWakeLock.isHeld()) {
5497 return;
5498 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005499 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005500 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5501 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005502 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005503 mWakelockLogs.log("ACQUIRE for " + forWhom);
5504 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005505 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005506 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005507 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005508 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005509
Hugo Benichi471b62a2017-03-30 23:18:10 +09005510 // Called when we gain a new default network to release the network transition wakelock in a
5511 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5512 // message is cancelled.
5513 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005514 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005515 if (!mNetTransitionWakeLock.isHeld()) {
5516 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005517 }
5518 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005519 // Cancel self timeout on wakelock hold.
5520 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5521 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5522 mHandler.sendMessageDelayed(msg, 1000);
5523 }
5524
5525 // Called when either message of ensureNetworkTransitionWakelock or
5526 // scheduleReleaseNetworkTransitionWakelock is processed.
5527 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5528 String event = eventName(eventId);
5529 synchronized (this) {
5530 if (!mNetTransitionWakeLock.isHeld()) {
5531 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005532 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005533 return;
5534 }
5535 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005536 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5537 mTotalWakelockDurationMs += lockDuration;
5538 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5539 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005540 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005541 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005542 }
5543
Robert Greenwalt986c7412010-09-08 15:24:47 -07005544 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005545 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005546 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005547 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005548 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005549 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005550 }
5551
Lorenzo Colittid6459092016-07-04 12:55:44 +09005552 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005553 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005554 enforceAccessPermission();
5555 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005556 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005557 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005558
5559 final NetworkAgentInfo nai;
5560 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005561 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005562 } else {
5563 nai = getNetworkAgentInfoForNetwork(network);
5564 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005565
5566 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005567 mHandler.obtainMessage(
5568 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005569 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005570
Hugo Benichid6b510a2017-04-06 17:22:18 +09005571 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005572 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005573 if (nai == null
5574 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005575 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005576 return;
5577 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005578 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005579 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005580 mConnectivityDiagnosticsHandler.sendMessage(
5581 mConnectivityDiagnosticsHandler.obtainMessage(
5582 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5583 new ReportedNetworkConnectivityInfo(
5584 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005585 return;
5586 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005587 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005588 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005589 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005590 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005591 // Validating a network that has not yet connected could result in a call to
5592 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005593 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005594 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005595 }
paulhu7aeba372020-12-30 00:42:19 +08005596 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5597 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005598 return;
5599 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005600
5601 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5602 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5603 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5604 // completed.
5605 mConnectivityDiagnosticsHandler.sendMessage(
5606 mConnectivityDiagnosticsHandler.obtainMessage(
5607 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5608 new ReportedNetworkConnectivityInfo(
5609 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005610 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005611 }
5612
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005613 // TODO: call into netd.
5614 private boolean queryUserAccess(int uid, Network network) {
5615 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5616 if (nai == null) return false;
5617
5618 // Any UID can use its default network.
5619 if (nai == getDefaultNetworkForUid(uid)) return true;
5620
5621 // Privileged apps can use any network.
5622 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5623 return true;
5624 }
5625
5626 // An unprivileged UID can use a VPN iff the VPN applies to it.
5627 if (nai.isVPN()) {
5628 return nai.networkCapabilities.appliesToUid(uid);
5629 }
5630
5631 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5632 // sockets, i.e., if it is the owner.
5633 final NetworkAgentInfo vpn = getVpnForUid(uid);
5634 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5635 && uid != vpn.networkCapabilities.getOwnerUid()) {
5636 return false;
5637 }
5638
5639 // The UID's permission must be at least sufficient for the network. Since the restricted
5640 // permission was already checked above, that just leaves background networks.
5641 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5642 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5643 }
5644
5645 // Unrestricted network. Anyone gets to use it.
5646 return true;
5647 }
5648
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005649 /**
5650 * Returns information about the proxy a certain network is using. If given a null network, it
5651 * it will return the proxy for the bound network for the caller app or the default proxy if
5652 * none.
5653 *
5654 * @param network the network we want to get the proxy information for.
5655 * @return Proxy information if a network has a proxy configured, or otherwise null.
5656 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005657 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005658 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005659 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005660 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005661 if (network == null) {
5662 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005663 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005664 true);
5665 if (activeNetwork == null) {
5666 return null;
5667 }
5668 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005669 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005670 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5671 // caller may not have.
5672 return getLinkPropertiesProxyInfo(network);
5673 }
5674 // No proxy info available if the calling UID does not have network access.
5675 return null;
5676 }
5677
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005678
5679 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005680 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5681 if (nai == null) return null;
5682 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005683 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5684 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005685 }
5686 }
5687
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005688 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005689 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005690 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005691 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005692 }
5693
Chalard Jean777e2e52018-06-07 18:02:37 +09005694 @Override
5695 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005696 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005697 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005698 }
5699
Junyu Lai970963e2022-10-25 15:46:47 +08005700 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005701 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005702 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005703 proxy = null;
5704 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09005705 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005706 }
5707
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005708 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
5709 // when any network changes proxy.
5710 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
5711 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08005712 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
5713 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05005714 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
5715
Chalard Jean7d97afc2018-06-07 17:41:29 +09005716 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09005717 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05005718 }
5719 }
5720
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005721 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09005722 final private HashMap<Uri, Integer> mUriEventMap;
5723 final private Context mContext;
5724 final private Handler mHandler;
5725
5726 SettingsObserver(Context context, Handler handler) {
5727 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09005728 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09005729 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005730 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005731 }
5732
Erik Kline05f2b402015-04-30 12:58:40 +09005733 void observe(Uri uri, int what) {
5734 mUriEventMap.put(uri, what);
5735 final ContentResolver resolver = mContext.getContentResolver();
5736 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005737 }
5738
5739 @Override
5740 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08005741 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09005742 }
5743
5744 @Override
5745 public void onChange(boolean selfChange, Uri uri) {
5746 final Integer what = mUriEventMap.get(uri);
5747 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09005748 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09005749 } else {
5750 loge("No matching event to send for URI=" + uri);
5751 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005752 }
5753 }
Wink Savillee70c6f52010-12-03 12:01:38 -08005754
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005755 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005756 Log.d(TAG, s);
5757 }
5758
5759 private static void logw(String s) {
5760 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005761 }
5762
Daniel Brightf9e945b2020-06-15 16:10:01 -07005763 private static void logwtf(String s) {
5764 Log.wtf(TAG, s);
5765 }
5766
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09005767 private static void logwtf(String s, Throwable t) {
5768 Log.wtf(TAG, s, t);
5769 }
5770
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07005771 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08005772 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08005773 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07005774
Hugo Benichi39621362017-02-11 17:04:43 +09005775 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08005776 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09005777 }
5778
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07005779 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005780 * Return the information of all ongoing VPNs.
5781 *
5782 * <p>This method is used to update NetworkStatsService.
5783 *
5784 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08005785 */
junyulai2050bed2021-01-23 09:46:34 +08005786 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08005787 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09005788 if (mLockdownEnabled) {
5789 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08005790 }
junyulai2050bed2021-01-23 09:46:34 +08005791 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005792 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08005793 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09005794 if (info != null) {
5795 infoList.add(info);
5796 }
5797 }
junyulai2050bed2021-01-23 09:46:34 +08005798 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08005799 }
5800
5801 /**
5802 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00005803 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08005804 */
junyulai2050bed2021-01-23 09:46:34 +08005805 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005806 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08005807 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
5808 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09005809 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
5810 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
5811 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08005812 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
5813 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00005814 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00005815 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08005816 }
5817 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005818
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005819 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005820
5821 List<String> interfaces = new ArrayList<>();
5822 for (Network network : underlyingNetworks) {
5823 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
5824 if (underlyingNai == null) continue;
5825 LinkProperties lp = underlyingNai.linkProperties;
5826 for (String iface : lp.getAllInterfaceNames()) {
5827 if (!TextUtils.isEmpty(iface)) {
5828 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00005829 }
5830 }
Benedict Wong34857f82019-06-12 17:46:15 +00005831 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005832
5833 if (interfaces.isEmpty()) return null;
5834
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005835 // Must be non-null or NetworkStatsService will crash.
5836 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
5837 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08005838 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08005839 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09005840
junyulai2050bed2021-01-23 09:46:34 +08005841 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
5842 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08005843 }
5844
James Mattisd31bdfa2020-12-23 16:37:26 -08005845 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08005846 private Network[] underlyingNetworksOrDefault(final int ownerUid,
5847 Network[] underlyingNetworks) {
5848 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005849 if (underlyingNetworks == null && defaultNetwork != null) {
5850 // null underlying networks means to track the default.
5851 underlyingNetworks = new Network[] { defaultNetwork };
5852 }
5853 return underlyingNetworks;
5854 }
5855
5856 // Returns true iff |network| is an underlying network of |nai|.
5857 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
5858 // TODO: support more than one level of underlying networks, either via a fixed-depth search
5859 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09005860 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08005861 final Network[] underlying = underlyingNetworksOrDefault(
5862 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09005863 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005864 }
5865
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005866 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005867 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005868 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005869 * When underlying networks change, such networks may have to update capabilities to reflect
5870 * things like the metered bit, their transports, and so on. The capabilities are calculated
5871 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005872 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005873 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09005874 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005875 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09005876 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09005877 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09005878 }
5879 }
5880 }
5881
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005882 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
5883 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
5884 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
5885 // a VPN is not up.
5886 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
5887 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
5888 for (UidRange range : blockedUidRanges) {
5889 if (range.contains(uid)) return true;
5890 }
5891 return false;
5892 }
5893
5894 @Override
5895 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08005896 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005897 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
5898 encodeBool(requireVpn), 0 /* arg2 */, ranges));
5899 }
5900
5901 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
5902 if (DBG) {
5903 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
5904 + Arrays.toString(ranges));
5905 }
5906 // Cannot use a Set since the list of UID ranges might contain duplicates.
5907 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
5908 for (int i = 0; i < ranges.length; i++) {
5909 if (requireVpn) {
5910 newVpnBlockedUidRanges.add(ranges[i]);
5911 } else {
5912 newVpnBlockedUidRanges.remove(ranges[i]);
5913 }
5914 }
5915
5916 try {
5917 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
5918 } catch (RemoteException | ServiceSpecificException e) {
5919 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
5920 + Arrays.toString(ranges) + "): netd command failed: " + e);
5921 }
5922
Motomu Utsumib08654c2022-05-11 05:56:26 +00005923 if (SdkLevel.isAtLeastT()) {
5924 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
5925 }
5926
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005927 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5928 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00005929 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
5930 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005931 }
5932
5933 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
5934 }
5935
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07005936 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005937 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08005938 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005939 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01005940 }
5941
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005942 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
5943 return mLockdownEnabled
5944 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
5945 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00005946 }
5947
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005948 private NetworkAgentInfo getLegacyLockdownNai() {
5949 if (!mLockdownEnabled) {
5950 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005951 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005952 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005953 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
5954 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00005955
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005956 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005957 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
5958 // a local variable. There is no need to make a copy because its contents cannot change.
5959 final Network[] underlying = nai.declaredUnderlyingNetworks;
5960 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005961 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005962 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005963
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005964 // The legacy lockdown VPN always uses the default network.
5965 // If the VPN's underlying network is no longer the current default network, it means that
5966 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005967 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
5968 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005969 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09005970 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005971 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005972 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005973
5974 return nai;
5975 };
5976
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005977 // TODO: move all callers to filterForLegacyLockdown and delete this method.
5978 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
5979 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09005980 private DetailedState getLegacyLockdownState(DetailedState origState) {
5981 if (origState != DetailedState.CONNECTED) {
5982 return origState;
5983 }
5984 return (mLockdownEnabled && getLegacyLockdownNai() == null)
5985 ? DetailedState.CONNECTING
5986 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00005987 }
5988
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09005989 private void filterForLegacyLockdown(NetworkInfo ni) {
5990 if (!mLockdownEnabled || !ni.isConnected()) return;
5991 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
5992 // state of its VPN. This is to ensure that when an underlying network connects, apps will
5993 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
5994 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
5995 // network, this time with a state of CONNECTED.
5996 //
5997 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
5998 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
5999 // is not too far off the truth, since an always-on VPN, when not connected, is always
6000 // trying to reconnect.
6001 if (getLegacyLockdownNai() == null) {
6002 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6003 }
6004 }
6005
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006006 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006007 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006008 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006009 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006010 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6011 return;
6012 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006013 final long ident = Binder.clearCallingIdentity();
6014 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006015 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006016 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006017 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006018 } finally {
6019 Binder.restoreCallingIdentity(ident);
6020 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006021 }
Wink Savillecb117d32013-08-29 14:57:08 -07006022
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006023 @Override
6024 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006025 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006026 final long ident = Binder.clearCallingIdentity();
6027 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006028 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006029 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006030 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6031 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006032 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006033 } finally {
6034 Binder.restoreCallingIdentity(ident);
6035 }
6036 }
6037
James Mattis02220e22021-03-13 19:27:21 -08006038 private void onUserAdded(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006039 mPermissionMonitor.onUserAdded(user);
James Mattisae9aeb02021-03-01 17:09:11 -08006040 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6041 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6042 }
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006043 }
6044
James Mattis02220e22021-03-13 19:27:21 -08006045 private void onUserRemoved(@NonNull final UserHandle user) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006046 mPermissionMonitor.onUserRemoved(user);
Chalard Jean0f57a492021-03-09 21:09:20 +09006047 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006048 handleSetProfileNetworkPreference(
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -08006049 List.of(new ProfileNetworkPreferenceList.Preference(user, null, true)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006050 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006051 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6052 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6053 }
junyulaid91e7052020-08-28 13:44:33 +08006054 }
6055
James Mattis02220e22021-03-13 19:27:21 -08006056 private void onPackageChanged(@NonNull final String packageName) {
6057 // This is necessary in case a package is added or removed, but also when it's replaced to
6058 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6059 // as one in the preferences, then it should follow the same routing as that other package,
6060 // which means updating the rules is never to be needed in this case (whether it joins or
6061 // leaves a UID with a preference).
6062 if (isMappedInOemNetworkPreference(packageName)) {
6063 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6064 }
6065 }
6066
6067 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006068 @Override
6069 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006070 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006071 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006072 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006073
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006074 // User should be filled for below intents, check the existence.
6075 if (user == null) {
6076 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6077 return;
6078 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006079
Lorenzo Colitticd675292021-02-04 17:32:07 +09006080 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006081 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006082 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006083 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006084 } else {
junyulaid91e7052020-08-28 13:44:33 +08006085 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006086 }
6087 }
6088 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006089
James Mattis02220e22021-03-13 19:27:21 -08006090 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6091 @Override
6092 public void onReceive(Context context, Intent intent) {
6093 ensureRunningOnConnectivityServiceThread();
6094 switch (intent.getAction()) {
6095 case Intent.ACTION_PACKAGE_ADDED:
6096 case Intent.ACTION_PACKAGE_REMOVED:
6097 case Intent.ACTION_PACKAGE_REPLACED:
6098 onPackageChanged(intent.getData().getSchemeSpecificPart());
6099 break;
6100 default:
6101 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6102 }
6103 }
6104 };
6105
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006106 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006107 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006108
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006109 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006110 public final String name;
6111 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006112 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006113 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006114
lifraf3a3492021-03-10 13:58:14 +08006115 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6116 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006117 this.name = name;
6118 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006119 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006120 mDeathRecipient = deathRecipient;
6121
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006122 if (mDeathRecipient == null) {
6123 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006124 }
6125 }
6126
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006127 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006128 try {
6129 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6130 } catch (RemoteException e) {
6131 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006132 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006133 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006134 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006135
James Mattis4fce5d12020-11-12 15:53:42 -08006136 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6137 for (int i = 0; i < requests.size(); i++) {
6138 ensureNetworkRequestHasType(requests.get(i));
6139 }
6140 }
6141
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006142 private void ensureNetworkRequestHasType(NetworkRequest request) {
6143 if (request.type == NetworkRequest.Type.NONE) {
6144 throw new IllegalArgumentException(
6145 "All NetworkRequests in ConnectivityService must have a type");
6146 }
6147 }
6148
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006149 /**
6150 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006151 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006152 */
James Mattis258ea3c2020-11-15 15:04:40 -08006153 @VisibleForTesting
6154 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006155 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6156 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006157 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006158
James Mattisa076c532020-12-02 14:12:41 -08006159 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6160 void setSatisfier(
6161 @Nullable final NetworkAgentInfo satisfier,
6162 @Nullable final NetworkRequest activeRequest) {
6163 mSatisfier = satisfier;
6164 mActiveRequest = activeRequest;
6165 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006166
James Mattisd31bdfa2020-12-23 16:37:26 -08006167 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006168 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006169 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006170 private NetworkAgentInfo mSatisfier;
6171 NetworkAgentInfo getSatisfier() {
6172 return mSatisfier;
6173 }
6174
6175 // The request in mRequests assigned to a network agent. This is null if none of the
6176 // requests in mRequests can be satisfied. This member has the constraint of only being
6177 // accessible on the handler thread.
6178 @Nullable
6179 private NetworkRequest mActiveRequest;
6180 NetworkRequest getActiveRequest() {
6181 return mActiveRequest;
6182 }
6183
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006184 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006185 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006186 @Nullable
6187 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006188
6189 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006190 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006191 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006192 final int mPid;
6193 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006194 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006195 @Nullable
6196 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006197
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006198 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006199 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006200
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006201 // Effective UID of this request. This is different from mUid when a privileged process
6202 // files a request on behalf of another UID. This UID is used to determine blocked status,
6203 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6204 // maximum limit of registered callbacks per UID.
6205 final int mAsUid;
6206
paulhu48291862021-07-14 14:53:57 +08006207 // Preference order of this request.
6208 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006209
James Mattis3ce3d3c2021-02-09 18:18:28 -08006210 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6211 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6212 // maintained for keying off of. This is only a concern when the original nri
6213 // mNetworkRequests changes which happens currently for apps that register callbacks to
6214 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6215 // that match the per-app default nri that currently tracks the calling app's uid so that
6216 // callbacks are fired at the appropriate time. When the callbacks fire,
6217 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6218 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6219 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6220 @NonNull
6221 private final NetworkRequest mNetworkRequestForCallback;
6222 NetworkRequest getNetworkRequestForCallback() {
6223 return mNetworkRequestForCallback;
6224 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006225
James Mattisd31bdfa2020-12-23 16:37:26 -08006226 /**
6227 * Get the list of UIDs this nri applies to.
6228 */
6229 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006230 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006231 // networkCapabilities.getUids() returns a defensive copy.
6232 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006233 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6234 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006235 }
6236
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006237 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6238 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006239 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006240 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006241 }
6242
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006243 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006244 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006245 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006246 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006247 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006248 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006249 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006250 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006251 mBinder = null;
6252 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006253 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006254 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006255 mPerUidCounter = getRequestCounter(this);
6256 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006257 /**
6258 * Location sensitive data not included in pending intent. Only included in
6259 * {@link NetworkCallback}.
6260 */
6261 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006262 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006263 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006264 }
6265
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006266 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006267 @Nullable final IBinder binder,
6268 @NetworkCallback.Flag int callbackFlags,
6269 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006270 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6271 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006272 }
6273
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006274 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006275 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006276 @Nullable final IBinder binder,
6277 @NetworkCallback.Flag int callbackFlags,
6278 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006279 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006280 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006281 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006282 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006283 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006284 mBinder = binder;
6285 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006286 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006287 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006288 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006289 mPerUidCounter = getRequestCounter(this);
6290 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006291 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006292 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006293 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006294 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006295 }
6296
James Mattis3ce3d3c2021-02-09 18:18:28 -08006297 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6298 @NonNull final List<NetworkRequest> r) {
6299 super();
6300 ensureAllNetworkRequestsHaveType(r);
6301 mRequests = initializeRequests(r);
6302 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006303 final NetworkAgentInfo satisfier = nri.getSatisfier();
6304 if (null != satisfier) {
6305 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6306 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006307 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006308 // As this code creates a new NRI with a new set of requests, figure out which of
6309 // the list of requests should be the active request. It is always the first
6310 // request of the list that can be satisfied by the satisfier since the order of
6311 // requests is a priority order.
6312 // Note even in the presence of a satisfier there may not be an active request,
6313 // when the satisfier is the no-service network.
6314 NetworkRequest activeRequest = null;
6315 for (final NetworkRequest candidate : r) {
6316 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6317 activeRequest = candidate;
6318 break;
6319 }
6320 }
6321 setSatisfier(satisfier, activeRequest);
6322 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006323 mMessenger = nri.mMessenger;
6324 mBinder = nri.mBinder;
6325 mPid = nri.mPid;
6326 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006327 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006328 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006329 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006330 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006331 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006332 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006333 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006334 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006335 }
6336
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006337 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006338 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006339 }
6340
paulhue9913722021-05-26 15:19:20 +08006341 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006342 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006343 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006344 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006345 }
6346
James Mattis2516da32021-01-31 17:06:19 -08006347 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6348 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6349 // false.
6350 boolean isBeingSatisfied() {
6351 return (null != mSatisfier && null != mActiveRequest);
6352 }
6353
James Mattis3d229892020-11-16 16:46:28 -08006354 boolean isMultilayerRequest() {
6355 return mRequests.size() > 1;
6356 }
6357
James Mattis45d81842021-01-10 14:24:24 -08006358 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6359 // Creating a defensive copy to prevent the sender from modifying the list being
6360 // reflected in the return value of this method.
6361 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006362 return Collections.unmodifiableList(tempRequests);
6363 }
6364
James Mattisb1392002021-03-31 13:57:52 -07006365 void linkDeathRecipient() {
6366 if (null != mBinder) {
6367 try {
6368 mBinder.linkToDeath(this, 0);
6369 } catch (RemoteException e) {
6370 binderDied();
6371 }
6372 }
6373 }
6374
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006375 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006376 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006377 try {
6378 mBinder.unlinkToDeath(this, 0);
6379 } catch (NoSuchElementException e) {
6380 // Temporary workaround for b/194394697 pending analysis of additional logs
6381 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6382 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006383 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006384 }
6385
paulhu48291862021-07-14 14:53:57 +08006386 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6387 // Compare two preference orders.
6388 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006389 }
6390
paulhu48291862021-07-14 14:53:57 +08006391 int getPreferenceOrderForNetd() {
6392 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6393 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6394 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006395 }
paulhu48291862021-07-14 14:53:57 +08006396 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006397 }
6398
James Mattis4fce5d12020-11-12 15:53:42 -08006399 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006400 public void binderDied() {
6401 log("ConnectivityService NetworkRequestInfo binderDied(" +
Chalard Jean524f0b12021-10-25 21:11:56 +09006402 "uid/pid:" + mUid + "/" + mPid + ", " + mRequests + ", " + mBinder + ")");
Chalard Jean5bcc8382021-07-19 19:57:02 +09006403 // As an immutable collection, mRequests cannot change by the time the
6404 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6405 // is acceptable. Use handleReleaseNetworkRequest and not directly
6406 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6407 // the app already unregistered the request.
6408 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6409 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006410 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006411
James Mattis4fce5d12020-11-12 15:53:42 -08006412 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006413 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006414 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6415 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006416 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006417 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006418 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006419 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006420 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006421 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006422 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006423 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006424 }
6425
Junyu Lai00d92df2022-07-05 11:01:52 +08006426 // Keep backward compatibility since the ServiceSpecificException is used by
6427 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6428 public static class RequestInfoPerUidCounter extends PerUidCounter {
6429 RequestInfoPerUidCounter(int maxCountPerUid) {
6430 super(maxCountPerUid);
6431 }
6432
6433 @Override
6434 public synchronized void incrementCountOrThrow(int uid) {
6435 try {
6436 super.incrementCountOrThrow(uid);
6437 } catch (IllegalStateException e) {
6438 throw new ServiceSpecificException(
6439 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6440 "Uid " + uid + " exceeded its allotted requests limit");
6441 }
6442 }
6443
6444 @Override
6445 public synchronized void decrementCountOrThrow(int uid) {
6446 throw new UnsupportedOperationException("Use decrementCount instead.");
6447 }
6448
6449 public synchronized void decrementCount(int uid) {
6450 try {
6451 super.decrementCountOrThrow(uid);
6452 } catch (IllegalStateException e) {
6453 logwtf("Exception when decrement per uid request count: ", e);
6454 }
6455 }
6456 }
6457
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006458 // This checks that the passed capabilities either do not request a
6459 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006460 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006461 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006462 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006463 throw new SecurityException("Insufficient permissions to request a specific SSID");
6464 }
paulhu1a407652019-03-22 16:35:06 +08006465
6466 if (nc.hasSignalStrength()
6467 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6468 throw new SecurityException(
6469 "Insufficient permissions to request a specific signal strength");
6470 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006471 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006472
junyulai2217bec2021-04-14 23:33:31 +08006473 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006474 enforceNetworkFactoryPermission();
6475 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006476 }
6477
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006478 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006479 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006480 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006481 // mNetworkRequests may contain the same value multiple times in case of
6482 // multilayer requests. It won't matter in this case because the thresholds
6483 // will then be the same and be deduplicated as they enter the `thresholds` set.
6484 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006485 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6486 for (final NetworkRequest req : nri.mRequests) {
6487 if (req.networkCapabilities.hasSignalStrength()
6488 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6489 thresholds.add(req.networkCapabilities.getSignalStrength());
6490 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006491 }
6492 }
6493 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006494 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006495 }
6496
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006497 private void updateSignalStrengthThresholds(
6498 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006499 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006500
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006501 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006502 String detail;
6503 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6504 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6505 } else {
6506 detail = reason;
6507 }
6508 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006509 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006510 }
6511
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006512 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006513 }
6514
Chalard Jeandd421992021-12-16 23:16:02 +09006515 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006516 if (nc == null) {
6517 return;
6518 }
6519 NetworkSpecifier ns = nc.getNetworkSpecifier();
6520 if (ns == null) {
6521 return;
6522 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006523 if (ns instanceof MatchAllNetworkSpecifier) {
6524 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6525 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006526 }
6527
Chalard Jeandd421992021-12-16 23:16:02 +09006528 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006529 ensureValidNetworkSpecifier(nc);
6530 if (nc.isPrivateDnsBroken()) {
6531 throw new IllegalArgumentException("Can't request broken private DNS");
6532 }
Chalard Jeande665262022-02-25 16:12:12 +09006533 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006534 throw new IllegalArgumentException("Can't request access UIDs");
6535 }
lucasline117e2e2019-10-22 18:27:33 +08006536 }
6537
Chalard Jeandd421992021-12-16 23:16:02 +09006538 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6539 ensureListenableCapabilities(nc);
6540 final String badCapability = nc.describeFirstNonRequestableCapability();
6541 if (badCapability != null) {
6542 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6543 }
6544 }
6545
Chiachang Wang3bc52762021-11-25 14:17:57 +08006546 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6547 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006548 private boolean isTargetSdkAtleast(int version, int callingUid,
6549 @NonNull String callingPackageName) {
6550 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006551 final PackageManager pm =
6552 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006553 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006554 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006555 if (callingVersion < version) return false;
6556 } catch (PackageManager.NameNotFoundException e) { }
6557 return true;
6558 }
6559
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006560 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006561 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006562 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006563 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006564 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006565 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006566 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6567 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006568 throw new SecurityException("Insufficient permissions to specify legacy type");
6569 }
markchienfac84a22020-03-18 21:16:15 +08006570 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006571 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006572 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006573 // Privileged callers can track the default network of another UID by passing in a UID.
6574 if (asUid != Process.INVALID_UID) {
6575 enforceSettingsPermission();
6576 } else {
6577 asUid = callingUid;
6578 }
junyulaiad010792021-01-11 16:53:38 +08006579 final NetworkRequest.Type reqType;
6580 try {
6581 reqType = NetworkRequest.Type.values()[reqTypeInt];
6582 } catch (ArrayIndexOutOfBoundsException e) {
6583 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6584 }
6585 switch (reqType) {
6586 case TRACK_DEFAULT:
6587 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006588 // is unused and will be replaced by ones appropriate for the UID (usually, the
6589 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006590 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006591 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006592 enforceAccessPermission();
6593 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006594 case TRACK_SYSTEM_DEFAULT:
6595 enforceSettingsPermission();
6596 networkCapabilities = new NetworkCapabilities(defaultNc);
6597 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006598 case BACKGROUND_REQUEST:
6599 enforceNetworkStackOrSettingsPermission();
6600 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006601 case REQUEST:
6602 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6603 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006604 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006605 // TODO: this is incorrect. We mark the request as metered or not depending on
6606 // the state of the app when the request is filed, but we never change the
6607 // request if the app changes network state. http://b/29964605
6608 enforceMeteredApnPolicy(networkCapabilities);
6609 break;
junyulai1b1c8742021-03-12 20:05:08 +08006610 case LISTEN_FOR_BEST:
6611 enforceAccessPermission();
6612 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6613 break;
junyulaiad010792021-01-11 16:53:38 +08006614 default:
6615 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006616 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006617 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006618 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006619 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006620
junyulai1b1c8742021-03-12 20:05:08 +08006621 // Enforce FOREGROUND if the caller does not have permission to use background network.
6622 if (reqType == LISTEN_FOR_BEST) {
6623 restrictBackgroundRequestForCaller(networkCapabilities);
6624 }
6625
6626 // Set the UID range for this request to the single UID of the requester, unless the
6627 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006628 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6629 // are no visible methods to set the UIDs, an app could use reflection to try and get
6630 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006631 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006632 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6633 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006634
Etan Cohen85000162017-02-05 10:42:27 -08006635 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006636 throw new IllegalArgumentException("Bad timeout specified");
6637 }
Etan Cohen9786d922015-11-18 10:56:15 -08006638
James Mattis3ce3d3c2021-02-09 18:18:28 -08006639 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006640 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006641 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006642 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006643 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006644 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006645
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006646 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6647 // copied from the default request above. (This is necessary to ensure, for example, that
6648 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6649 // changes don't alter request matching.
6650 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6651 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006652 throw new IllegalStateException(
6653 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006654 + networkCapabilities + " vs. " + defaultNc);
6655 }
6656
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006657 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006658 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006659 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006660 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006661 }
6662 return networkRequest;
6663 }
6664
James Mattis3ce3d3c2021-02-09 18:18:28 -08006665 /**
6666 * Return the nri to be used when registering a network request. Specifically, this is used with
6667 * requests registered to track the default request. If there is currently a per-app default
6668 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6669 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006670 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6671 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006672 * @param nr the network request for the nri.
6673 * @param msgr the messenger for the nri.
6674 * @param binder the binder for the nri.
6675 * @param callingAttributionTag the calling attribution tag for the nri.
6676 * @return the nri to register.
6677 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006678 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006679 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006680 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006681 @Nullable String callingAttributionTag) {
6682 final List<NetworkRequest> requests;
6683 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6684 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006685 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006686 } else {
6687 requests = Collections.singletonList(nr);
6688 }
Roshan Pius951c0032020-12-22 15:10:42 -08006689 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006690 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006691 }
6692
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006693 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08006694 String callingPackageName, String callingAttributionTag, final int callingUid) {
Lorenzo Colittie97685a2015-05-14 17:28:27 +09006695 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08006696 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
6697 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
6698 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
6699 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08006700 }
junyulai96bd9fe2022-03-08 17:36:42 +08006701 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006702 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006703 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006704 }
6705 }
6706
fenglu3f357402015-03-20 11:29:56 -07006707 @Override
fenglub00f4882015-04-21 17:12:05 -07006708 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07006709 enforceAccessPermission();
6710 NetworkAgentInfo nai = null;
6711 if (network == null) {
6712 return false;
6713 }
6714 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006715 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07006716 }
6717 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006718 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006719 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006720 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006721 Integer uidReqs = mBandwidthRequests.get(uid);
6722 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006723 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07006724 }
6725 mBandwidthRequests.put(uid, ++uidReqs);
6726 }
fenglu3f357402015-03-20 11:29:56 -07006727 return true;
6728 }
6729 return false;
6730 }
6731
Felipe Leme0a5ae422016-06-20 16:36:29 -07006732 private boolean isSystem(int uid) {
6733 return uid < Process.FIRST_APPLICATION_UID;
6734 }
fenglu3f357402015-03-20 11:29:56 -07006735
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006736 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006737 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07006738 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09006739 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07006740 return;
6741 }
Hugo Benichi39621362017-02-11 17:04:43 +09006742 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
6743 // Policy already enforced.
6744 return;
6745 }
paulhuaf50d7d2020-12-24 19:47:34 +08006746 final long ident = Binder.clearCallingIdentity();
6747 try {
6748 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
6749 // If UID is restricted, don't allow them to bring up metered APNs.
6750 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
6751 }
6752 } finally {
6753 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006754 }
6755 }
6756
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006757 @Override
6758 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006759 PendingIntent operation, @NonNull String callingPackageName,
6760 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006761 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006762 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006763 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07006764 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006765 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006766 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006767 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006768 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006769 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006770 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6771 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09006772
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006773 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006774 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006775 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6776 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006777 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006778 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
6779 nri));
6780 return networkRequest;
6781 }
6782
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006783 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
6784 mHandler.sendMessageDelayed(
6785 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006786 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006787 }
6788
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006789 @Override
6790 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006791 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006792 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006793 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006794 }
6795
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006796 // In order to implement the compatibility measure for pre-M apps that call
6797 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
6798 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
6799 // This ensures it has permission to do so.
6800 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
6801 if (nc == null) {
6802 return false;
6803 }
6804 int[] transportTypes = nc.getTransportTypes();
6805 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
6806 return false;
6807 }
6808 try {
6809 mContext.enforceCallingOrSelfPermission(
6810 android.Manifest.permission.ACCESS_WIFI_STATE,
6811 "ConnectivityService");
6812 } catch (SecurityException e) {
6813 return false;
6814 }
6815 return true;
6816 }
6817
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006818 @Override
6819 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08006820 Messenger messenger, IBinder binder,
6821 @NetworkCallback.Flag int callbackFlags,
6822 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006823 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09006824 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6825 enforceAccessPermission();
6826 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006827
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006828 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006829 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006830 Binder.getCallingPid(), callingUid, callingPackageName);
6831 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09006832 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
6833 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
6834 // onLost and onAvailable callbacks when networks move in and out of the background.
6835 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
6836 // can't request networks.
6837 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09006838 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07006839
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09006840 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006841 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08006842 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006843 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08006844 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006845 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006846
6847 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
6848 return networkRequest;
6849 }
6850
6851 @Override
6852 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08006853 PendingIntent operation, @NonNull String callingPackageName,
6854 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00006855 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006856 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04006857 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
6858 enforceAccessPermission();
6859 }
Chalard Jeandd421992021-12-16 23:16:02 +09006860 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006861 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006862 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006863 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08006864 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006865
6866 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09006867 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006868 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
6869 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006870 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04006871
WeiZhang1cc3f172021-06-03 19:02:04 -05006872 mHandler.sendMessage(mHandler.obtainMessage(
6873 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006874 }
6875
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006876 /** Returns the next Network provider ID. */
6877 public final int nextNetworkProviderId() {
6878 return mNextNetworkProviderId.getAndIncrement();
6879 }
6880
Erik Kline0c04b742016-07-07 16:50:58 +09006881 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006882 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006883 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09006884 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09006885 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006886 }
6887
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006888 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
6889 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006890 // Avoid creating duplicates. even if an app makes a direct AIDL call.
6891 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
6892 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08006893 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006894 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006895 return;
6896 }
6897
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006898 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
6899 mNetworkProviderInfos.put(npi.messenger, npi);
6900 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006901 }
6902
6903 @Override
6904 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006905 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08006906 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006907 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08006908 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006909 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
6910 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006911 }
6912
6913 @Override
6914 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006915 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006916 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006917 }
6918
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006919 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09006920 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006921 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
6922 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09006923 Objects.requireNonNull(score);
6924 Objects.requireNonNull(caps);
6925 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09006926 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006927 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09006928 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
6929 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006930 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
6931 }
6932
Chalard Jeanbb902a52021-08-18 01:35:19 +09006933 private void updateOfferScore(final NetworkOffer offer) {
6934 final boolean yieldToBadWiFi =
6935 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
6936 final NetworkOffer newOffer = new NetworkOffer(
6937 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
6938 offer.caps, offer.callback, offer.providerId);
6939 if (offer.equals(newOffer)) return;
6940 handleRegisterNetworkOffer(newOffer);
6941 }
6942
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006943 @Override
6944 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08006945 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006946 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
6947 }
6948
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006949 private void handleUnregisterNetworkProvider(Messenger messenger) {
6950 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
6951 if (npi == null) {
6952 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006953 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006954 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006955 // Unregister all the offers from this provider
6956 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
6957 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09006958 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006959 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
6960 toRemove.add(noi);
6961 }
6962 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09006963 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006964 handleUnregisterNetworkOffer(noi);
6965 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006966 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006967 }
6968
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006969 @Override
James Mattisf7027322020-12-13 16:28:14 -08006970 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08006971 if (request.hasTransport(TRANSPORT_TEST)) {
6972 enforceNetworkFactoryOrTestNetworksPermission();
6973 } else {
6974 enforceNetworkFactoryPermission();
6975 }
James Mattisf7027322020-12-13 16:28:14 -08006976 final NetworkRequestInfo nri = mNetworkRequests.get(request);
6977 if (nri != null) {
6978 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
6979 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
6980 mHandler.post(() -> handleReleaseNetworkRequest(
6981 nri.mRequests.get(0), mDeps.getCallingUid(), true));
6982 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006983 }
6984
Paul Jensen1f567382015-02-13 14:18:39 -05006985 // NOTE: Accessed on multiple threads, must be synchronized on itself.
6986 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006987 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05006988 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006989 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05006990 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006991 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006992
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09006993 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05006994 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006995 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006996
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006997 // UID ranges for users that are currently blocked by VPNs.
6998 // This array is accessed and iterated on multiple threads without holding locks, so its
6999 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7000 // (on the handler thread).
7001 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7002
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007003 // Must only be accessed on the handler thread
7004 @NonNull
7005 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7006
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007007 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007008 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007009
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007010 // Current OEM network preferences. This object must only be written to on the handler thread.
7011 // Since it is immutable and always non-null, other threads may read it if they only care
7012 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007013 @NonNull
7014 private OemNetworkPreferences mOemNetworkPreferences =
7015 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007016 // Current per-profile network preferences. This object follows the same threading rules as
7017 // the OEM network preferences above.
7018 @NonNull
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007019 private ProfileNetworkPreferenceList mProfileNetworkPreferences =
7020 new ProfileNetworkPreferenceList();
James Mattis45d81842021-01-10 14:24:24 -08007021
paulhu51f77dc2021-06-07 02:34:20 +00007022 // A set of UIDs that should use mobile data preferentially if available. This object follows
7023 // the same threading rules as the OEM network preferences above.
7024 @NonNull
7025 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7026
James Mattiscb1e0362021-04-06 17:07:42 -07007027 // OemNetworkPreferences activity String log entries.
7028 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7029 @NonNull
7030 private final LocalLog mOemNetworkPreferencesLogs =
7031 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7032
James Mattis02220e22021-03-13 19:27:21 -08007033 /**
7034 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7035 * @param packageName the package name to check existence of a mapping for.
7036 * @return true if a mapping exists, false otherwise
7037 */
7038 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7039 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7040 }
7041
James Mattise3ef1912020-12-20 11:09:58 -08007042 // The always-on request for an Internet-capable network that apps without a specific default
7043 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007044 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007045 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007046 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007047 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007048 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007049 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007050 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007051
James Mattisd31bdfa2020-12-23 16:37:26 -08007052 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7053 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7054 }
7055
7056 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007057 * Return the default network request currently tracking the given uid.
7058 * @param uid the uid to check.
7059 * @return the NetworkRequestInfo tracking the given uid.
7060 */
7061 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007062 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007063 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007064 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007065 // Checking the first request is sufficient as only multilayer requests will have more
7066 // than one request and for multilayer, all requests will track the same uids.
7067 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007068 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007069 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007070 highestPriorityNri = nri;
7071 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007072 }
7073 }
paulhuaa0743d2021-05-26 21:56:03 +08007074 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007075 }
7076
7077 /**
7078 * Get a copy of the network requests of the default request that is currently tracking the
7079 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007080 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7081 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007082 * @param requestorUid the uid to check the default for.
7083 * @param requestorPackageName the requestor's package name.
7084 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7085 */
7086 @NonNull
7087 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007088 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007089 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007090 getDefaultRequestTrackingUid(asUid).mRequests,
7091 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007092 }
7093
7094 /**
7095 * Copy the given nri's NetworkRequest collection.
7096 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007097 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7098 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007099 * @param requestorUid the uid to set on the copied collection.
7100 * @param requestorPackageName the package name to set on the copied collection.
7101 * @return the copied NetworkRequest collection.
7102 */
7103 @NonNull
7104 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007105 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7106 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007107 final List<NetworkRequest> requests = new ArrayList<>();
7108 for (final NetworkRequest nr : requestsToCopy) {
7109 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007110 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007111 nr.legacyType, nextNetworkRequestId(), nr.type));
7112 }
7113 return requests;
7114 }
7115
7116 @NonNull
7117 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007118 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7119 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007120 // These capabilities are for a TRACK_DEFAULT callback, so:
7121 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7122 // mDefaultRequest and a per-UID default request.
7123 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007124 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007125 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007126 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7127 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007128 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007129 restrictRequestUidsForCallerAndSetRequestorInfo(
7130 netCap, requestorUid, requestorPackageName);
7131 return netCap;
7132 }
7133
7134 /**
7135 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7136 * @param nr the network request to check for equality against.
7137 * @return the nri if one exists, null otherwise.
7138 */
7139 @Nullable
7140 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7141 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7142 if (nri.getNetworkRequestForCallback().equals(nr)) {
7143 return nri;
7144 }
7145 }
7146 return null;
7147 }
7148
7149 /**
7150 * Check if an nri is currently being managed by per-app default networking.
7151 * @param nri the nri to check.
7152 * @return true if this nri is currently being managed by per-app default networking.
7153 */
7154 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7155 // nri.mRequests.get(0) is only different from the original request filed in
7156 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7157 // functionality therefore if these two don't match, it means this particular nri is
7158 // currently being managed by a per-app default.
7159 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7160 }
7161
7162 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007163 * Determine if an nri is a managed default request that disallows default networking.
7164 * @param nri the request to evaluate
7165 * @return true if device-default networking is disallowed
7166 */
7167 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7168 // Check if this nri is a managed default that supports the default network at its
7169 // lowest priority request.
7170 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7171 final NetworkCapabilities lowestPriorityNetCap =
7172 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7173 return isPerAppDefaultRequest(nri)
7174 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7175 lowestPriorityNetCap));
7176 }
7177
Erik Kline05f2b402015-04-30 12:58:40 +09007178 // Request used to optionally keep mobile data active even when higher
7179 // priority networks like Wi-Fi are active.
7180 private final NetworkRequest mDefaultMobileDataRequest;
7181
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007182 // Request used to optionally keep wifi data active even when higher
7183 // priority networks like ethernet are active.
7184 private final NetworkRequest mDefaultWifiRequest;
7185
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007186 // Request used to optionally keep vehicle internal network always active
7187 private final NetworkRequest mDefaultVehicleRequest;
7188
James Mattisd31bdfa2020-12-23 16:37:26 -08007189 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7190 // network with no service. This NAI should never be matched against, nor should any public API
7191 // ever return the associated network. For this reason, this NAI is not in the list of available
7192 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7193 // default requests that don't support using the device default network which will ultimately
7194 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7195 @VisibleForTesting
7196 final NetworkAgentInfo mNoServiceNetwork;
7197
Chalard Jean5b409c72021-02-04 13:12:59 +09007198 // The NetworkAgentInfo currently satisfying the default request, if any.
7199 private NetworkAgentInfo getDefaultNetwork() {
7200 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007201 }
7202
James Mattis2516da32021-01-31 17:06:19 -08007203 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007204 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007205 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7206 // Currently, all network requests will have the same uids therefore checking the first
7207 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007208 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007209 if (null == uids) {
7210 continue;
7211 }
7212 for (final UidRange range : uids) {
7213 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007214 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007215 highestPriorityNri = nri;
7216 }
James Mattis2516da32021-01-31 17:06:19 -08007217 }
7218 }
7219 }
paulhuaa0743d2021-05-26 21:56:03 +08007220 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007221 }
7222
Varun Ananddf569952019-02-06 10:13:38 -08007223 @Nullable
7224 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7225 return nai != null ? nai.network : null;
7226 }
7227
7228 private void ensureRunningOnConnectivityServiceThread() {
7229 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7230 throw new IllegalStateException(
7231 "Not running on ConnectivityService thread: "
7232 + Thread.currentThread().getName());
7233 }
7234 }
7235
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007236 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007237 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7238 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007239 }
7240
Chalard Jean29d06db2018-05-02 21:14:54 +09007241 /**
7242 * Register a new agent with ConnectivityService to handle a network.
7243 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007244 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007245 * @param networkInfo the initial info associated with this network. It can be updated later :
7246 * see {@link #updateNetworkInfo}.
7247 * @param linkProperties the initial link properties of this network. They can be updated
7248 * later : see {@link #updateLinkProperties}.
7249 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007250 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007251 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007252 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007253 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007254 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007255 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007256 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007257 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007258 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7259 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007260 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7261 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7262 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007263 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007264 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007265 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007266 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007267 } else {
7268 enforceNetworkFactoryPermission();
7269 }
7270
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007271 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007272 final long token = Binder.clearCallingIdentity();
7273 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007274 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007275 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007276 } finally {
7277 Binder.restoreCallingIdentity(token);
7278 }
7279 }
7280
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007281 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007282 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007283 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7284 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007285
Chalard Jeandbc46952022-02-02 00:14:18 +09007286 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7287 // and mutate them at any time.
7288 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7289 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7290 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7291
Chalard Jean366c5252022-01-25 18:27:53 +09007292 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007293 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007294 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7295 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007296 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007297 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007298 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007299 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7300 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007301
Chalard Jeandbc46952022-02-02 00:14:18 +09007302 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007303 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007304 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007305 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007306 mDeps.getNetworkStack().makeNetworkMonitor(
7307 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007308 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7309 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007310 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007311 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007312 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007313 }
7314
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007315 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007316 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007317 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007318 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007319 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007320 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7321 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7322 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007323
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007324 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007325
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007326 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007327 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007328 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007329 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007330
7331 try {
7332 networkMonitor.start();
7333 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007334 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007335 }
Chalard Jean366c5252022-01-25 18:27:53 +09007336
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007337 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007338 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007339 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007340 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007341 }
7342
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007343 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7344 @NonNull public final NetworkOffer offer;
7345
7346 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7347 this.offer = offer;
7348 }
7349
7350 @Override
7351 public void binderDied() {
7352 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7353 }
7354 }
7355
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007356 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7357 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7358 if (npi.providerId == providerId) return true;
7359 }
7360 return false;
7361 }
7362
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007363 /**
7364 * Register or update a network offer.
7365 * @param newOffer The new offer. If the callback member is the same as an existing
7366 * offer, it is an update of that offer.
7367 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007368 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007369 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7370 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007371 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007372 // This may actually happen if a provider updates its score or registers and then
7373 // immediately unregisters. The offer would still be in the handler queue, but the
7374 // provider would have been removed.
7375 if (DBG) log("Received offer from an unregistered provider");
7376 return;
7377 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007378 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7379 if (null != existingOffer) {
7380 handleUnregisterNetworkOffer(existingOffer);
7381 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007382 if (DBG) {
7383 // handleUnregisterNetworkOffer has already logged the old offer
7384 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7385 }
7386 } else {
7387 if (DBG) {
7388 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7389 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007390 }
7391 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7392 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007393 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007394 } catch (RemoteException e) {
7395 noi.binderDied();
7396 return;
7397 }
7398 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007399 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007400 }
7401
7402 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7403 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007404 if (DBG) {
7405 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7406 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007407
7408 // If the provider removes the offer and dies immediately afterwards this
7409 // function may be called twice in a row, but the array will no longer contain
7410 // the offer.
7411 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007412 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007413 }
7414
7415 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7416 @NonNull final INetworkOfferCallback callback) {
7417 ensureRunningOnConnectivityServiceThread();
7418 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007419 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007420 }
7421 return null;
7422 }
7423
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007424 /**
7425 * Called when receiving LinkProperties directly from a NetworkAgent.
7426 * Stores into |nai| any data coming from the agent that might also be written to the network's
7427 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7428 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007429 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007430 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007431 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7432 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007433 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007434 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007435 }
7436
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007437 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007438 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007439 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007440
Lorenzo Colittid523d142020-04-01 20:16:30 +09007441 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7442 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7443 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007444 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007445
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007446 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007447
7448 // update filtering rules, need to happen after the interface update so netd knows about the
7449 // new interface (the interface name -> index map becomes initialized)
7450 updateVpnFiltering(newLp, oldLp, networkAgent);
7451
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007452 updateMtu(newLp, oldLp);
7453 // TODO - figure out what to do for clat
7454// for (LinkProperties lp : newLp.getStackedLinks()) {
7455// updateMtu(lp, null);
7456// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007457 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007458 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7459 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007460
Erik Klineb9888902016-04-05 13:30:49 +09007461 updateRoutes(newLp, oldLp, netId);
7462 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007463 // Make sure LinkProperties represents the latest private DNS status.
7464 // This does not need to be done before updateDnses because the
7465 // LinkProperties are not the source of the private DNS configuration.
7466 // updateDnses will fetch the private DNS configuration from DnsManager.
7467 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007468
Chalard Jean5b409c72021-02-04 13:12:59 +09007469 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007470 handleApplyDefaultProxy(newLp.getHttpProxy());
7471 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007472 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007473 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007474
7475 updateWakeOnLan(newLp);
7476
Hai Shalome58bdc62021-01-11 18:45:34 -08007477 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7478 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7479 // does, it needs to be merged here.
7480 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7481 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007482
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007483 // TODO - move this check to cover the whole function
7484 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007485 synchronized (networkAgent) {
7486 networkAgent.linkProperties = newLp;
7487 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007488 // Start or stop DNS64 detection and 464xlat according to network state.
7489 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007490 // Notify NSS when relevant events happened. Currently, NSS only cares about
7491 // interface changed to update clat interfaces accounting.
7492 final boolean interfacesChanged = oldLp == null
7493 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7494 if (interfacesChanged) {
7495 notifyIfacesChangedForNetworkStats();
7496 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007497 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7498 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007499 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007500 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007501
7502 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007503 }
7504
Hai Shalome58bdc62021-01-11 18:45:34 -08007505 /**
7506 * @param naData captive portal data from NetworkAgent
7507 * @param apiData captive portal data from capport API
7508 */
7509 @Nullable
7510 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7511 CaptivePortalData apiData) {
7512 if (naData == null || apiData == null) {
7513 return naData == null ? apiData : naData;
7514 }
7515 final CaptivePortalData.Builder captivePortalBuilder =
7516 new CaptivePortalData.Builder(naData);
7517
7518 if (apiData.isCaptive()) {
7519 captivePortalBuilder.setCaptive(true);
7520 }
7521 if (apiData.isSessionExtendable()) {
7522 captivePortalBuilder.setSessionExtendable(true);
7523 }
7524 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7525 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7526 // otherwise data would be inconsistent. Prefer the capport API info if present,
7527 // as it can generally be refreshed more often.
7528 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7529 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7530 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7531 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7532 // No source has time / bytes remaining information: surface the newest refresh time
7533 // for other fields
7534 captivePortalBuilder.setRefreshTime(
7535 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7536 }
7537
Hai Shalom7c6ab402021-02-04 19:34:06 -08007538 // Prioritize the user portal URL from the network agent if the source is authenticated.
7539 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7540 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7541 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7542 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007543 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007544 // Prioritize the venue information URL from the network agent if the source is
7545 // authenticated.
7546 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7547 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7548 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7549 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007550 }
7551 return captivePortalBuilder.build();
7552 }
7553
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007554 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007555 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007556 // marks on unsupported interfaces is harmless.
7557 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
7558 return;
7559 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007560
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007561 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7562 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7563
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007564 // Mask/mark of zero will not detect anything interesting.
7565 // Don't install rules unless both values are nonzero.
7566 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007567 return;
7568 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007569
7570 final String prefix = "iface:" + iface;
7571 try {
7572 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007573 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007574 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007575 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007576 }
7577 } catch (Exception e) {
7578 loge("Exception modifying wakeup packet monitoring: " + e);
7579 }
7580
Joel Scherpelza235a812017-05-22 13:47:41 +09007581 }
7582
Junyu Lai970963e2022-10-25 15:46:47 +08007583 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09007584 final @Nullable LinkProperties oldLp, final int netId,
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007585 final @NonNull NetworkCapabilities caps) {
Chalard Jean9589e722019-11-19 19:03:53 +09007586 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08007587 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09007588 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007589 for (final String iface : interfaceDiff.added) {
7590 try {
7591 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007592 mNetd.networkAddInterface(netId, iface);
Chalard Jean9589e722019-11-19 19:03:53 +09007593 wakeupModifyInterface(iface, caps, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007594 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
7595 caps.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007596 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007597 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007598 }
Paul Jensenbff73492014-04-28 10:33:11 -04007599 }
7600 }
Chalard Jean9589e722019-11-19 19:03:53 +09007601 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007602 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007603 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007604 wakeupModifyInterface(iface, caps, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007605 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007606 } catch (Exception e) {
7607 loge("Exception removing interface: " + e);
7608 }
7609 }
7610 }
7611
Tyler Weare4314862019-12-05 14:55:30 -08007612 // TODO: move to frameworks/libs/net.
7613 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7614 final String nextHop;
7615
7616 switch (route.getType()) {
7617 case RouteInfo.RTN_UNICAST:
7618 if (route.hasGateway()) {
7619 nextHop = route.getGateway().getHostAddress();
7620 } else {
7621 nextHop = INetd.NEXTHOP_NONE;
7622 }
7623 break;
7624 case RouteInfo.RTN_UNREACHABLE:
7625 nextHop = INetd.NEXTHOP_UNREACHABLE;
7626 break;
7627 case RouteInfo.RTN_THROW:
7628 nextHop = INetd.NEXTHOP_THROW;
7629 break;
7630 default:
7631 nextHop = INetd.NEXTHOP_NONE;
7632 break;
7633 }
7634
7635 final RouteInfoParcel rip = new RouteInfoParcel();
7636 rip.ifName = route.getInterface();
7637 rip.destination = route.getDestination().toString();
7638 rip.nextHop = nextHop;
7639 rip.mtu = route.getMtu();
7640
7641 return rip;
7642 }
7643
Paul Jensene0fd4a82014-08-06 15:51:33 -04007644 /**
7645 * Have netd update routes from oldLp to newLp.
7646 * @return true if routes changed between oldLp and newLp
7647 */
Junyu Lai970963e2022-10-25 15:46:47 +08007648 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7649 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08007650 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08007651 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
7652 new CompareOrUpdateResult<>(
7653 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08007654 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08007655 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007656
7657 // add routes before removing old in case it helps with continuous connectivity
7658
Chalard Jean9dd11612018-06-04 16:52:49 +09007659 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007660 for (RouteInfo route : routeDiff.added) {
7661 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007662 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007663 try {
Tyler Weare4314862019-12-05 14:55:30 -08007664 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007665 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007666 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007667 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007668 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007669 }
7670 }
7671 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007672 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007673 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007674 try {
Tyler Weare4314862019-12-05 14:55:30 -08007675 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007676 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007677 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08007678 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007679 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007680 }
7681 }
7682
7683 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09007684 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007685 try {
Tyler Weare4314862019-12-05 14:55:30 -08007686 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007687 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08007688 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007689 }
7690 }
Tyler Weare4314862019-12-05 14:55:30 -08007691
7692 for (RouteInfo route : routeDiff.updated) {
7693 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
7694 try {
7695 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
7696 } catch (Exception e) {
7697 loge("Exception in networkUpdateRouteParcel: " + e);
7698 }
7699 }
7700 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
7701 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007702 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09007703
Junyu Lai970963e2022-10-25 15:46:47 +08007704 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7705 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09007706 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
7707 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007708 }
Erik Klineb9888902016-04-05 13:30:49 +09007709
Erik Kline31b4a9e2018-01-11 21:07:29 +09007710 if (DBG) {
7711 final Collection<InetAddress> dnses = newLp.getDnsServers();
7712 log("Setting DNS servers for network " + netId + " to " + dnses);
7713 }
Erik Klineb9888902016-04-05 13:30:49 +09007714 try {
chenbruce7b2f8982020-02-20 14:28:31 +08007715 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08007716 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09007717 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09007718 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09007719 }
Erik Kline54e35c02017-04-07 15:29:29 +09007720 }
7721
Junyu Lai970963e2022-10-25 15:46:47 +08007722 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
7723 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00007724 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
7725 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00007726 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
7727 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007728
7729 if (!wasFiltering && !needsFiltering) {
7730 // Nothing to do.
7731 return;
7732 }
7733
7734 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
7735 // Nothing changed.
7736 return;
7737 }
7738
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007739 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00007740 if (ranges == null || ranges.isEmpty()) {
7741 return;
7742 }
7743
Qingxi Libb8da982020-01-17 17:54:27 -08007744 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007745 // TODO: this create a window of opportunity for apps to receive traffic between the time
7746 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06007747 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007748 // old rules are being removed.
7749 if (wasFiltering) {
7750 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
7751 }
7752 if (needsFiltering) {
7753 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
7754 }
7755 }
7756
Valentin Iftime9fa35092019-09-24 13:32:13 +02007757 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007758 if (mWolSupportedInterfaces == null) {
7759 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007760 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09007761 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007762 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
7763 }
7764
Luke Huangb913c812018-08-24 20:33:16 +08007765 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007766 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08007767 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007768 }
7769 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08007770 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007771 }
Luke Huangb913c812018-08-24 20:33:16 +08007772 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007773 }
7774
Chalard Jean62edfd82019-12-02 18:39:29 +09007775 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
7776 @NonNull final NetworkCapabilities newNc) {
7777 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
7778 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09007779 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09007780 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007781 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08007782 } catch (RemoteException | ServiceSpecificException e) {
7783 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09007784 }
7785 }
7786 }
7787
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007788 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007789 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09007790 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007791 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08007792 underlyingNetworks = underlyingNetworksOrDefault(
7793 agentCaps.getOwnerUid(), underlyingNetworks);
lifrade6c2a2021-03-04 14:08:08 +08007794 long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007795 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
7796 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007797 // metered if any underlying is metered, or originally declared metered by the agent.
7798 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007799 boolean roaming = false; // roaming if any underlying is roaming
7800 boolean congested = false; // congested if any underlying is congested
7801 boolean suspended = true; // suspended if all underlying are suspended
7802
7803 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08007804 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007805 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08007806 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007807 for (Network underlyingNetwork : underlyingNetworks) {
7808 final NetworkAgentInfo underlying =
7809 getNetworkAgentInfoForNetwork(underlyingNetwork);
7810 if (underlying == null) continue;
7811
7812 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
7813 hadUnderlyingNetworks = true;
7814 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007815 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007816 }
7817
7818 // Merge capabilities of this underlying network. For bandwidth, assume the
7819 // worst case.
7820 downKbps = NetworkCapabilities.minBandwidth(downKbps,
7821 underlyingCaps.getLinkDownstreamBandwidthKbps());
7822 upKbps = NetworkCapabilities.minBandwidth(upKbps,
7823 underlyingCaps.getLinkUpstreamBandwidthKbps());
7824 // If this underlying network is metered, the VPN is metered (it may cost money
7825 // to send packets on this network).
7826 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
7827 // If this underlying network is roaming, the VPN is roaming (the billing structure
7828 // is different than the usual, local one).
7829 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7830 // If this underlying network is congested, the VPN is congested (the current
7831 // condition of the network affects the performance of this network).
7832 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
7833 // If this network is not suspended, the VPN is not suspended (the VPN
7834 // is able to transfer some data).
7835 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08007836 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007837 }
7838 }
7839 if (!hadUnderlyingNetworks) {
7840 // No idea what the underlying networks are; assume reasonable defaults
7841 metered = true;
7842 roaming = false;
7843 congested = false;
7844 suspended = false;
7845 }
7846
lifrade6c2a2021-03-04 14:08:08 +08007847 newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007848 newNc.setLinkDownstreamBandwidthKbps(downKbps);
7849 newNc.setLinkUpstreamBandwidthKbps(upKbps);
7850 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
7851 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
7852 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
7853 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08007854 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09007855 }
7856
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007857 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007858 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
7859 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
7860 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04007861 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007862 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007863 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09007864 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007865 // Don't complain for VPNs since they're not driven by requests and there is no risk of
7866 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007867 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09007868 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09007869 if (nai.everConnected()
7870 && !nai.isVPN()
7871 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007872 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09007873 // does not cause any request (that is not a listen) currently matching that agent to
7874 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007875 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09007876 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08007877 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09007878 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007879 }
7880
Paul Jensen53f08952015-06-16 14:27:36 -04007881 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007882 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09007883 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007884 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007885 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007886 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04007887 }
Chalard Jean254bd162022-08-25 13:04:51 +09007888 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007889 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007890 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007891 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04007892 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007893 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007894 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007895 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007896 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007897 }
Chalard Jean254bd162022-08-25 13:04:51 +09007898 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08007899 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7900 } else {
7901 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
7902 }
lucasline117e2e2019-10-22 18:27:33 +08007903 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007904
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007905 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09007906 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
7907 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09007908 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09007909 }
7910
Lorenzo Colittibd079452021-07-02 11:47:57 +09007911 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09007912 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09007913 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007914 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007915 }
7916
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007917 return newNc;
7918 }
7919
Lorenzo Colitti44840702021-01-11 22:27:57 +09007920 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
7921 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
7922 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7923 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
7924 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7925 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
7926 if (prevSuspended != suspended) {
7927 // TODO (b/73132094) : remove this call once the few users of onSuspended and
7928 // onResumed have been removed.
7929 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
7930 : ConnectivityManager.CALLBACK_RESUMED);
7931 }
7932 if (prevSuspended != suspended || prevRoaming != roaming) {
7933 // updateNetworkInfo will mix in the suspended info from the capabilities and
7934 // take appropriate action for the network having possibly changed state.
7935 updateNetworkInfo(nai, nai.networkInfo);
7936 }
7937 }
7938
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007939 /**
7940 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
7941 *
7942 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
7943 * capabilities we manage and store in {@code nai}, such as validated status and captive
7944 * portal status)
7945 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
7946 * potentially triggers rematches.
7947 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
7948 * change.)
7949 *
7950 * @param oldScore score of the network before any of the changes that prompted us
7951 * to call this function.
7952 * @param nai the network having its capabilities updated.
7953 * @param nc the new network capabilities.
7954 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007955 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09007956 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007957 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09007958 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean62edfd82019-12-02 18:39:29 +09007959 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09007960 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007961
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007962 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09007963 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09007964 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09007965
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007966 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007967 // If the requestable capabilities haven't changed, and the score hasn't changed, then
7968 // the change we're processing can't affect any requests, it can only affect the listens
7969 // on this network. We might have been called by rematchNetworkAndRequests when a
7970 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09007971 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09007972 } else {
7973 // If the requestable capabilities have changed or the score changed, we can't have been
7974 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09007975 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04007976 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07007977 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09007978 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06007979
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007980 final boolean oldMetered = prevNc.isMetered();
7981 final boolean newMetered = newNc.isMetered();
7982 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08007983
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007984 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00007985 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
7986 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007987 }
junyulaif2c67e42018-08-07 19:50:45 +08007988
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007989 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
7990 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08007991
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09007992 // Report changes that are interesting for network statistics tracking.
7993 if (meteredChanged || roamingChanged) {
7994 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06007995 }
7996
Lorenzo Colitti96dba632020-12-02 00:48:09 +09007997 // This network might have been underlying another network. Propagate its capabilities.
7998 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08007999
8000 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008001 mDnsManager.updateTransportsForNetwork(
8002 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008003 }
lucaslin53e8a262021-06-08 01:43:59 +08008004
8005 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008006 }
8007
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008008 /** Convenience method to update the capabilities for a given network. */
8009 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008010 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008011 }
8012
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008013 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008014 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008015 *
8016 * Ingress interface filtering enforces that all apps under the given network can only receive
8017 * packets from the network's interface (and loopback). This is important for VPNs because
8018 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8019 * non-VPN interfaces.
8020 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008021 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008022 * 1. the network is an app VPN (not legacy VPN)
8023 * 2. the VPN does not allow bypass
8024 * 3. the VPN is fully-routed
8025 * 4. the VPN interface is non-null
8026 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008027 * @see INetd#firewallAddUidInterfaceRules
8028 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008029 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008030 @Nullable
8031 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008032 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008033 if (nc == null || lp == null) return null;
8034 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008035 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008036 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008037 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008038 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008039 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008040 && !lp.hasExcludeRoute()) {
8041 return lp.getInterfaceName();
8042 }
8043 return null;
8044 }
8045
8046 /**
8047 * Returns whether we need to set interface filtering rule or not
8048 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008049 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008050 String isolationIface) {
8051 // Allow rules are always needed if VPN isolation is enabled.
8052 if (isolationIface != null) return true;
8053
8054 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8055 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8056 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8057 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008058 }
8059
Chiachang Wang28afaff2020-12-10 22:24:47 +08008060 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8061 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8062 int index = 0;
8063 for (UidRange range : ranges) {
8064 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8065 index++;
8066 }
8067 return stableRanges;
8068 }
8069
Chalard Jeane6c95272022-01-25 21:04:21 +09008070 private static UidRangeParcel[] intsToUidRangeStableParcels(
8071 final @NonNull ArraySet<Integer> uids) {
8072 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8073 int index = 0;
8074 for (int uid : uids) {
8075 stableRanges[index] = new UidRangeParcel(uid, uid);
8076 index++;
8077 }
8078 return stableRanges;
8079 }
8080
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008081 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8082 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8083 for (int i = 0; i < ranges.length; i++) {
8084 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8085 }
8086 return stableRanges;
8087 }
8088
Ken Chen5e65a852020-12-24 12:59:10 +08008089 private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
8090 int[] exemptUids) {
8091 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8092 try {
8093 mNetd.socketDestroy(ranges, exemptUids);
8094 } catch (Exception e) {
8095 loge("Exception in socket destroy: ", e);
8096 }
8097 }
8098 }
8099
paulhuaa0743d2021-05-26 21:56:03 +08008100 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Ken Chen5e65a852020-12-24 12:59:10 +08008101 int[] exemptUids = new int[2];
8102 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8103 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8104 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
8105 exemptUids[0] = VPN_UID;
8106 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
8107 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8108
8109 maybeCloseSockets(nai, ranges, exemptUids);
8110 try {
8111 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008112 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008113 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008114 } else {
paulhu0e79d952021-06-09 16:11:35 +08008115 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008116 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008117 }
8118 } catch (Exception e) {
8119 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8120 " on netId " + nai.network.netId + ". " + e);
8121 }
8122 maybeCloseSockets(nai, ranges, exemptUids);
8123 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008124
lucaslin53e8a262021-06-08 01:43:59 +08008125 private boolean isProxySetOnAnyDefaultNetwork() {
8126 ensureRunningOnConnectivityServiceThread();
8127 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8128 final NetworkAgentInfo nai = nri.getSatisfier();
8129 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8130 return true;
8131 }
8132 }
8133 return false;
8134 }
8135
8136 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8137 NetworkCapabilities newNc) {
8138 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8139 // the proxy might be changed since the default network satisfied by the apps might also
8140 // changed.
8141 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8142 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008143 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8144 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008145 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008146 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8147 mProxyTracker.sendProxyBroadcast();
8148 }
8149 }
8150
Chalard Jeane6c95272022-01-25 21:04:21 +09008151 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8152 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008153 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8154 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008155 if (null == prevRanges) prevRanges = new ArraySet<>();
8156 if (null == newRanges) newRanges = new ArraySet<>();
8157 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8158
8159 prevRanges.removeAll(newRanges);
8160 newRanges.removeAll(prevRangesCopy);
8161
8162 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008163 // When updating the VPN uid routing rules, add the new range first then remove the old
8164 // range. If old range were removed first, there would be a window between the old
8165 // range being removed and the new range being added, during which UIDs contained
8166 // in both ranges are not subject to any VPN routing rules. Adding new range before
8167 // removing old range works because, unlike the filtering rules below, it's possible to
8168 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008169 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8170 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8171 // [1-5] & [1-2],[4-5] == [3]
8172 // Then we can do:
8173 // maybeCloseSockets([3])
8174 // mNetd.networkAddUidRanges([1-2],[4-5])
8175 // mNetd.networkRemoveUidRanges([1-5])
8176 // maybeCloseSockets([3])
8177 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8178 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008179 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008180 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008181 }
8182 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008183 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008184 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008185 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8186 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008187 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8188 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008189 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008190 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008191 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8192 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8193 // were added first and then newRanges got removed later, there would be only one uid
8194 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8195 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8196 // Note that this is in contrast with the (more robust) update of VPN routing rules
8197 // above, where the addition of new ranges happens before the removal of old ranges.
8198 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8199 // to be removed will never overlap with the new range to be added.
8200 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008201 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8202 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008203 }
8204 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008205 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008206 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008207 } catch (Exception e) {
8208 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008209 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008210 }
8211 }
8212
Chalard Jeande665262022-02-25 16:12:12 +09008213 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008214 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8215 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008216 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8217 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008218 if (prevEmpty && newEmpty) return;
8219
8220 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008221 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008222 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008223 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008224
8225 if (prevUids.equals(newUids)) return;
8226
8227 // This implementation is very simple and vastly faster for sets of Integers than
8228 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8229 // a key computed from the value and has storage for that.
8230 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8231 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8232 toRemove.removeAll(newUids);
8233 toAdd.removeAll(prevUids);
8234
8235 try {
8236 if (!toAdd.isEmpty()) {
8237 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8238 nai.network.netId,
8239 intsToUidRangeStableParcels(toAdd),
8240 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8241 }
8242 if (!toRemove.isEmpty()) {
8243 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8244 nai.network.netId,
8245 intsToUidRangeStableParcels(toRemove),
8246 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8247 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008248 } catch (ServiceSpecificException e) {
8249 // Has the interface disappeared since the network was built ?
8250 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008251 } catch (RemoteException e) {
8252 // Netd died. This usually causes a runtime restart anyway.
8253 }
8254 }
8255
Junyu Lai2ed7d412022-10-07 16:52:21 +08008256 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8257 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008258 ensureRunningOnConnectivityServiceThread();
8259
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008260 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008261 // Ignore updates for disconnected networks
8262 return;
8263 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008264 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008265 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008266 + "; created=" + nai.getCreatedTime()
8267 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008268 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008269 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8270 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008271 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008272 }
8273
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008274 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8275 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008276 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008277 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008278 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008279 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8280 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8281 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008282 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8283 // need to be sent as a separate extra.
8284 final NetworkRequest req = nri.isMultilayerRequest()
8285 ? nri.getActiveRequest()
8286 // Non-multilayer listen requests do not have an active request
8287 : nri.mRequests.get(0);
8288 if (req == null) {
8289 Log.wtf(TAG, "No request in NRI " + nri);
8290 }
8291 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008292 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008293 sendIntent(nri.mPendingIntent, intent);
8294 }
8295 // else not handled
8296 }
8297
8298 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8299 mPendingIntentWakeLock.acquire();
8300 try {
8301 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008302 final BroadcastOptions options = BroadcastOptions.makeBasic();
8303 if (SdkLevel.isAtLeastT()) {
8304 // Explicitly disallow the receiver from starting activities, to prevent apps from
8305 // utilizing the PendingIntent as a backdoor to do this.
8306 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8307 }
8308 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8309 null /* requiredPermission */,
8310 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008311 } catch (PendingIntent.CanceledException e) {
8312 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8313 mPendingIntentWakeLock.release();
8314 releasePendingNetworkRequest(pendingIntent);
8315 }
8316 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8317 }
8318
8319 @Override
8320 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8321 String resultData, Bundle resultExtras) {
8322 if (DBG) log("Finished sending " + pendingIntent);
8323 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008324 // Release with a delay so the receiving client has an opportunity to put in its
8325 // own request.
8326 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008327 }
8328
Chalard Jean46bfbf02022-02-02 00:56:25 +09008329 // networkAgent is only allowed to be null if notificationType is
8330 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8331 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008332 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008333 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008334 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008335 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008336 // Default request has no msgr. Also prevents callbacks from being invoked for
8337 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8338 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8339 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008340 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008341 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008342 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008343 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008344 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008345 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008346 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008347 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8348 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008349 }
Roshan Pius951c0032020-12-22 15:10:42 -08008350 final boolean includeLocationSensitiveInfo =
8351 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008352 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008353 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008354 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008355 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008356 networkCapabilitiesRestrictedForCallerPermissions(
8357 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8358 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008359 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008360 nri.mCallingAttributionTag);
8361 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008362 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8363 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008364 // For this notification, arg1 contains the blocked status.
8365 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008366 break;
8367 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008368 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008369 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008370 break;
8371 }
8372 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008373 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008374 final NetworkCapabilities netCap =
8375 networkCapabilitiesRestrictedForCallerPermissions(
8376 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8377 putParcelable(
8378 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008379 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008380 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008381 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008382 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008383 break;
8384 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008385 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008386 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8387 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008388 break;
8389 }
junyulaif2c67e42018-08-07 19:50:45 +08008390 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008391 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008392 msg.arg1 = arg1;
8393 break;
8394 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008395 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008396 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008397 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008398 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008399 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008400 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008401 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008402 }
James Mattis45d81842021-01-10 14:24:24 -08008403 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008404 } catch (RemoteException e) {
8405 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008406 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008407 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008408 }
8409
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008410 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8411 bundle.putParcelable(t.getClass().getSimpleName(), t);
8412 }
8413
Chalard Jean0702f982021-09-16 21:50:07 +09008414 /**
8415 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8416 *
8417 * When a request should be assigned to a new network, it is normally lingered to give
8418 * time for apps to gracefully migrate their connections. When both networks are on the same
8419 * radio, but that radio can't do time-sharing efficiently, this may end up being
8420 * counter-productive because any traffic on the old network may drastically reduce the
8421 * performance of the new network.
8422 * The stack supports a configuration to let modem vendors state that their radio can't
8423 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8424 * from one cell network to another can't be done gracefully.
8425 *
8426 * @param oldNai the old network serving the request
8427 * @param newNai the new network serving the request
8428 * @return whether the switch can be graceful
8429 */
8430 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8431 @NonNull final NetworkAgentInfo newSatisfier) {
8432 if (mCellularRadioTimesharingCapable) return true;
8433 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8434 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8435 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8436 }
8437
Paul Jensenaf94b982014-09-30 15:37:41 -04008438 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008439 if (nai.numRequestNetworkRequests() != 0) {
8440 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8441 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008442 // Ignore listening and track default requests.
8443 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008444 loge("Dead network still had at least " + nr);
8445 break;
8446 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008447 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008448 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008449 }
8450
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008451 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8452 if (oldNetwork == null) {
8453 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8454 return;
8455 }
Chalard Jean49707572019-12-10 21:07:02 +09008456 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008457
8458 // If we get here it means that the last linger timeout for this network expired. So there
8459 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008460 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008461
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008462 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008463 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008464 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008465 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008466 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008467 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008468 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008469 }
8470
James Mattise3ef1912020-12-20 11:09:58 -08008471 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8472 boolean isDefaultChanged = false;
8473 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8474 final NetworkReassignment.RequestReassignment reassignment =
8475 changes.getReassignment(defaultRequestInfo);
8476 if (null == reassignment) {
8477 continue;
8478 }
8479 // reassignment only contains those instances where the satisfying network changed.
8480 isDefaultChanged = true;
8481 // Notify system services of the new default.
8482 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8483 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008484
James Mattise3ef1912020-12-20 11:09:58 -08008485 if (isDefaultChanged) {
8486 // Hold a wakelock for a short time to help apps in migrating to a new default.
8487 scheduleReleaseNetworkTransitionWakelock();
8488 }
8489 }
8490
8491 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8492 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8493 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8494 if (DBG) {
8495 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8496 }
Chalard Jean8e382112019-12-03 20:45:30 +09008497
James Mattisd31bdfa2020-12-23 16:37:26 -08008498 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8499 if (newDefaultNetwork != null) {
8500 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008501 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008502
James Mattisd31bdfa2020-12-23 16:37:26 -08008503 // Set an app level managed default and return since further processing only applies to the
8504 // default network.
8505 if (mDefaultRequest != nri) {
8506 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8507 return;
8508 }
8509
8510 makeDefaultNetwork(newDefaultNetwork);
8511
James Mattise3ef1912020-12-20 11:09:58 -08008512 if (oldDefaultNetwork != null) {
8513 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8514 }
8515 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008516 handleApplyDefaultProxy(null != newDefaultNetwork
8517 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8518 updateTcpBufferSizes(null != newDefaultNetwork
8519 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008520 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008521 }
8522
James Mattisd31bdfa2020-12-23 16:37:26 -08008523 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8524 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8525 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8526 try {
8527 if (VDBG) {
8528 log("Setting default network for " + nri
8529 + " using UIDs " + nri.getUids()
8530 + " with old network " + (oldDefaultNetwork != null
8531 ? oldDefaultNetwork.network().getNetId() : "null")
8532 + " and new network " + (newDefaultNetwork != null
8533 ? newDefaultNetwork.network().getNetId() : "null"));
8534 }
8535 if (nri.getUids().isEmpty()) {
8536 throw new IllegalStateException("makeDefaultForApps called without specifying"
8537 + " any applications to set as the default." + nri);
8538 }
8539 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008540 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008541 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008542 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008543 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008544 }
8545 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008546 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008547 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008548 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008549 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008550 }
8551 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008552 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008553 }
8554 }
8555
8556 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
8557 try {
8558 if (null != newDefaultNetwork) {
8559 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
8560 } else {
8561 mNetd.networkClearDefault();
8562 }
8563 } catch (RemoteException | ServiceSpecificException e) {
8564 loge("Exception setting default network :" + e);
8565 }
8566 }
8567
Chalard Jean05cbe972019-12-09 11:50:38 +09008568 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008569 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09008570 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09008571 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09008572 processNewlySatisfiedListenRequests(nai);
8573 }
8574
8575 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008576 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8577 if (nri.isMultilayerRequest()) {
8578 continue;
8579 }
8580 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008581 if (!nr.isListen()) continue;
8582 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08008583 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008584 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
8585 }
8586 }
Chalard Jeancd397a22019-11-22 22:33:33 +09008587 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008588
Chalard Jeancd397a22019-11-22 22:33:33 +09008589 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08008590 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8591 if (nri.isMultilayerRequest()) {
8592 continue;
8593 }
8594 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008595 if (!nr.isListen()) continue;
8596 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
8597 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09008598 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09008599 }
8600 }
8601 }
8602
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008603 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008604 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008605 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08008606 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09008607 @Nullable public final NetworkRequest mOldNetworkRequest;
8608 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008609 @Nullable public final NetworkAgentInfo mOldNetwork;
8610 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08008611 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008612 @Nullable final NetworkRequest oldNetworkRequest,
8613 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008614 @Nullable final NetworkAgentInfo oldNetwork,
8615 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008616 mNetworkRequestInfo = networkRequestInfo;
8617 mOldNetworkRequest = oldNetworkRequest;
8618 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008619 mOldNetwork = oldNetwork;
8620 mNewNetwork = newNetwork;
8621 }
Chalard Jean49707572019-12-10 21:07:02 +09008622
8623 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09008624 final NetworkRequest requestToShow = null != mNewNetworkRequest
8625 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
8626 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08008627 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
8628 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09008629 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008630 }
8631
Chalard Jean46a62372019-12-10 21:25:24 +09008632 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008633
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008634 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09008635 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008636 }
8637
8638 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09008639 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09008640 // The code is never supposed to add two reassignments of the same request. Make
8641 // sure this stays true, but without imposing this expensive check on all
8642 // reassignments on all user devices.
8643 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08008644 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09008645 throw new IllegalStateException("Trying to reassign ["
8646 + reassignment + "] but already have ["
8647 + existing + "]");
8648 }
8649 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09008650 }
Chalard Jean46a62372019-12-10 21:25:24 +09008651 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008652 }
8653
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008654 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09008655 // the passed request.
8656 @Nullable
8657 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008658 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008659 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09008660 }
8661 return null;
8662 }
Chalard Jean49707572019-12-10 21:07:02 +09008663
8664 public String toString() {
8665 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
8666 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09008667 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008668 for (final RequestReassignment rr : getRequestReassignments()) {
8669 sj.add(rr.toString());
8670 }
8671 return sj.toString();
8672 }
8673
8674 public String debugString() {
8675 final StringBuilder sb = new StringBuilder();
8676 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09008677 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09008678 for (final RequestReassignment rr : getRequestReassignments()) {
8679 sb.append("\n ").append(rr);
8680 }
8681 return sb.append("\n").toString();
8682 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09008683 }
8684
Chalard Jean24344d72019-12-04 13:32:31 +09008685 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09008686 @Nullable final NetworkRequest previousRequest,
8687 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09008688 @Nullable final NetworkAgentInfo previousSatisfier,
8689 @Nullable final NetworkAgentInfo newSatisfier,
8690 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08008691 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09008692 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09008693 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008694 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008695 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09008696 }
James Mattisa076c532020-12-02 14:12:41 -08008697 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008698 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09008699 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09008700 // If this network switch can't be supported gracefully, the request is not
8701 // lingered. This allows letting go of the network sooner to reclaim some
8702 // performance on the new network, since the radio can't do both at the same
8703 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09008704 //
8705 // Also don't linger the request if the old network has been destroyed.
8706 // A destroyed network does not provide actual network connectivity, so
8707 // lingering it is not useful. In particular this ensures that a destroyed
8708 // network is outscored by its replacement,
8709 // then it is torn down immediately instead of being lingered, and any apps that
8710 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09008711 previousSatisfier.lingerRequest(previousRequest.requestId, now);
8712 }
Chalard Jean24344d72019-12-04 13:32:31 +09008713 } else {
8714 if (VDBG || DDBG) log(" accepting network in place of null");
8715 }
junyulai0ac374f2020-12-14 18:41:52 +08008716
8717 // To prevent constantly CPU wake up for nascent timer, if a network comes up
8718 // and immediately satisfies a request then remove the timer. This will happen for
8719 // all networks except in the case of an underlying network for a VCN.
8720 if (newSatisfier.isNascent()) {
8721 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08008722 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08008723 }
8724
Chalard Jean5d6e23b2021-03-01 22:00:20 +09008725 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08008726 newSatisfier.unlingerRequest(newRequest.requestId);
8727 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008728 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08008729 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008730 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09008731 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09008732 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008733 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08008734 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008735 }
James Mattisa076c532020-12-02 14:12:41 -08008736 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09008737 }
James Mattisa076c532020-12-02 14:12:41 -08008738 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09008739 }
8740
James Mattisa076c532020-12-02 14:12:41 -08008741 /**
8742 * This function is triggered when something can affect what network should satisfy what
8743 * request, and it computes the network reassignment from the passed collection of requests to
8744 * network match to the one that the system should now have. That data is encoded in an
8745 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
8746 * satisfier.
8747 *
8748 * After the reassignment is computed, it is applied to the state objects.
8749 *
8750 * @param networkRequests the nri objects to evaluate for possible network reassignment
8751 * @return NetworkReassignment listing of proposed network assignment changes
8752 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008753 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08008754 private NetworkReassignment computeNetworkReassignment(
8755 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09008756 final NetworkReassignment changes = new NetworkReassignment();
8757
Chalard Jeanc81d4c32021-04-07 17:06:19 +09008758 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09008759 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008760 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09008761 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09008762 }
Chalard Jean857a1712019-12-10 21:08:07 +09008763
James Mattisa076c532020-12-02 14:12:41 -08008764 for (final NetworkRequestInfo nri : networkRequests) {
8765 // Non-multilayer listen requests can be ignored.
8766 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
8767 continue;
8768 }
8769 NetworkAgentInfo bestNetwork = null;
8770 NetworkRequest bestRequest = null;
8771 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09008772 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08008773 // Stop evaluating as the highest possible priority request is satisfied.
8774 if (null != bestNetwork) {
8775 bestRequest = req;
8776 break;
8777 }
8778 }
James Mattisd31bdfa2020-12-23 16:37:26 -08008779 if (null == bestNetwork && isDefaultBlocked(nri)) {
8780 // Remove default networking if disallowed for managed default requests.
8781 bestNetwork = mNoServiceNetwork;
8782 }
8783 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09008784 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09008785 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08008786 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09008787 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008788 }
8789 return changes;
8790 }
8791
James Mattisa076c532020-12-02 14:12:41 -08008792 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
8793 return new HashSet<>(mNetworkRequests.values());
8794 }
8795
Paul Jensenc88b39b2015-06-16 14:27:36 -04008796 /**
James Mattisa076c532020-12-02 14:12:41 -08008797 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04008798 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04008799 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008800 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08008801 rematchNetworksAndRequests(getNrisFromGlobalRequests());
8802 }
8803
8804 /**
8805 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
8806 * being disconnected.
8807 */
8808 private void rematchNetworksAndRequests(
8809 @NonNull final Set<NetworkRequestInfo> networkRequests) {
8810 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09008811 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09008812 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08008813 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09008814 final long computed = SystemClock.elapsedRealtime();
8815 applyNetworkReassignment(changes, start);
8816 final long applied = SystemClock.elapsedRealtime();
8817 issueNetworkNeeds();
8818 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09008819 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008820 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
8821 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008822 log(changes.debugString());
8823 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09008824 // Shorter form, only one line of log
8825 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
8826 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09008827 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09008828 }
Chalard Jean64520dc2019-12-04 19:55:32 +09008829
Chalard Jeand7f762d2019-12-10 19:01:29 +09008830 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09008831 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008832 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09008833
8834 // Since most of the time there are only 0 or 1 background networks, it would probably
8835 // be more efficient to just use an ArrayList here. TODO : measure performance
8836 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
8837 for (final NetworkAgentInfo nai : nais) {
8838 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
8839 }
8840
Chalard Jeand7f762d2019-12-10 19:01:29 +09008841 // First, update the lists of satisfied requests in the network agents. This is necessary
8842 // because some code later depends on this state to be correct, most prominently computing
8843 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09008844 for (final NetworkReassignment.RequestReassignment event :
8845 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08008846 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
8847 event.mOldNetworkRequest, event.mNewNetworkRequest,
8848 event.mOldNetwork, event.mNewNetwork,
8849 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09008850 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008851
James Mattise3ef1912020-12-20 11:09:58 -08008852 // Process default network changes if applicable.
8853 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008854
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008855 // Notify requested networks are available after the default net is switched, but
8856 // before LegacyTypeTracker sends legacy broadcasts
8857 for (final NetworkReassignment.RequestReassignment event :
8858 changes.getRequestReassignments()) {
8859 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08008860 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008861 } else {
James Mattisa076c532020-12-02 14:12:41 -08008862 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09008863 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09008864 }
8865 }
8866
junyulai0ac374f2020-12-14 18:41:52 +08008867 // Update the inactivity state before processing listen callbacks, because the background
8868 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008869 // just yet though, because they have to be sent after the listens are processed to keep
8870 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08008871 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09008872 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08008873 // Rematching may have altered the inactivity state of some networks, so update all
8874 // inactivity timers. updateInactivityState reads the state from the network agent
8875 // and does nothing if the state has not changed : the source of truth is controlled
8876 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
8877 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08008878 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08008879 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008880 }
8881 }
8882
Chalard Jeanb10ab412019-12-11 14:12:30 +09008883 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008884 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008885 // Process listen requests and update capabilities if the background state has
8886 // changed for this network. For consistency with previous behavior, send onLost
8887 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09008888 processNewlyLostListenRequests(nai);
8889 if (oldBackground != nai.isBackgroundNetwork()) {
8890 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008891 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09008892 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09008893 }
8894
junyulai0ac374f2020-12-14 18:41:52 +08008895 for (final NetworkAgentInfo nai : inactiveNetworks) {
8896 // For nascent networks, if connecting with no foreground request, skip broadcasting
8897 // LOSING for backward compatibility. This is typical when mobile data connected while
8898 // wifi connected with mobile data always-on enabled.
8899 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008900 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008901 }
8902
James Mattise3ef1912020-12-20 11:09:58 -08008903 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09008904
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09008905 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008906 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008907 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08008908 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09008909 // This network has active linger timers and no requests, but is not
8910 // lingering. Linger it.
8911 //
8912 // One way (the only way?) this can happen if this network is unvalidated
8913 // and became unneeded due to another network improving its score to the
8914 // point where this network will no longer be able to satisfy any requests
8915 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08008916 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09008917 notifyNetworkLosing(nai, now);
8918 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09008919 } else {
Chalard Jean49707572019-12-10 21:07:02 +09008920 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09008921 teardownUnneededNetwork(nai);
8922 }
8923 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04008924 }
8925 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008926
Chalard Jean62edfd82019-12-02 18:39:29 +09008927 /**
8928 * Apply a change in background state resulting from rematching networks with requests.
8929 *
8930 * During rematch, a network may change background states by starting to satisfy or stopping
8931 * to satisfy a foreground request. Listens don't count for this. When a network changes
8932 * background states, its capabilities need to be updated and callbacks fired for the
8933 * capability change.
8934 *
8935 * @param nai The network that changed background states
8936 */
8937 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
8938 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
8939 if (Objects.equals(nai.networkCapabilities, newNc)) return;
8940 updateNetworkPermissions(nai, newNc);
8941 nai.getAndSetNetworkCapabilities(newNc);
8942 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
8943 }
8944
Chalard Jeanf0344532019-11-19 19:23:38 +09008945 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08008946 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09008947 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09008948 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
8949 changes.getReassignment(mDefaultRequest);
8950 final NetworkAgentInfo oldDefaultNetwork =
8951 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
8952 final NetworkAgentInfo newDefaultNetwork =
8953 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08008954
Chalard Jean5b409c72021-02-04 13:12:59 +09008955 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008956 // Maintain the illusion : since the legacy API only understands one network at a time,
8957 // if the default network changed, apps should see a disconnected broadcast for the
8958 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09008959 if (oldDefaultNetwork != null) {
8960 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
8961 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008962 }
Chalard Jean5b409c72021-02-04 13:12:59 +09008963 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09008964 // The new default network can be newly null if and only if the old default
8965 // network doesn't satisfy the default request any more because it lost a
8966 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09008967 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08008968 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09008969 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09008970 }
8971 }
8972
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008973 // Now that all the callbacks have been sent, send the legacy network broadcasts
8974 // as needed. This is necessary so that legacy requests correctly bind dns
8975 // requests to this network. The legacy users are listening for this broadcast
8976 // and will generally do a dns request so they can ensureRouteToHost and if
8977 // they do that before the callbacks happen they'll use the default network.
8978 //
8979 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
8980 // callbacks, but if apps can receive the broadcast before the callback, they still might
8981 // have an inconsistent view of networking.
8982 //
8983 // This *does* introduce a race where if the user uses the new api
8984 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
8985 // they may get old info. Reverse this after the old startUsing api is removed.
8986 // This is on top of the multiple intent sequencing referenced in the todo above.
8987 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09008988 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09008989 addNetworkToLegacyTypeTracker(nai);
8990 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08008991 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008992 }
8993
Chalard Jean0354d8c2021-01-12 10:58:56 +09008994 private void issueNetworkNeeds() {
8995 ensureRunningOnConnectivityServiceThread();
8996 for (final NetworkOfferInfo noi : mNetworkOffers) {
8997 issueNetworkNeeds(noi);
8998 }
8999 }
9000
9001 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9002 ensureRunningOnConnectivityServiceThread();
9003 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9004 informOffer(nri, noi.offer, mNetworkRanker);
9005 }
9006 }
9007
9008 /**
9009 * Inform a NetworkOffer about any new situation of a request.
9010 *
9011 * This function handles updates to offers. A number of events may happen that require
9012 * updating the registrant for this offer about the situation :
9013 * • The offer itself was updated. This may lead the offer to no longer being able
9014 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9015 * or conversely being strengthened enough to beat the satisfier (and therefore
9016 * start being needed)
9017 * • The network satisfying a request changed (including cases where the request
9018 * starts or stops being satisfied). The new network may be a stronger or weaker
9019 * match than the old one, possibly affecting whether the offer is needed.
9020 * • The network satisfying a request updated their score. This may lead the offer
9021 * to no longer be able to beat it if the current satisfier got better, or
9022 * conversely start being a good choice if the current satisfier got weaker.
9023 *
9024 * @param nri The request
9025 * @param offer The offer. This may be an updated offer.
9026 */
9027 private static void informOffer(@NonNull NetworkRequestInfo nri,
9028 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9029 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9030 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009031
9032 // Multi-layer requests have a currently active request, the one being satisfied.
9033 // Since the system will try to bring up a better network than is currently satisfying
9034 // the request, NetworkProviders need to be told the offers matching the requests *above*
9035 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9036 // not needed, and the offer is needed for the active request iff the offer can beat
9037 // the satisfier.
9038 // For non-multilayer requests, the logic above gracefully degenerates to only the
9039 // last case.
9040 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9041 // providers that the offer is needed for this request, until the active request is found.
9042 // In a second phase, deal with the currently active request. In a third phase, inform
9043 // the providers that offer is unneeded for the remaining requests.
9044
9045 // First phase : inform providers of all requests above the active request.
9046 int i;
9047 for (i = 0; nri.mRequests.size() > i; ++i) {
9048 final NetworkRequest request = nri.mRequests.get(i);
9049 if (activeRequest == request) break; // Found the active request : go to phase 2
9050 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9051 // Since this request is higher-priority than the one currently satisfied, if the
9052 // offer can satisfy it, the provider should try and bring up the network for sure ;
9053 // no need to even ask the ranker – an offer that can satisfy is always better than
9054 // no network. Hence tell the provider so unless it already knew.
9055 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9056 offer.onNetworkNeeded(request);
9057 }
9058 }
9059
9060 // Second phase : deal with the active request (if any)
9061 if (null != activeRequest && activeRequest.isRequest()) {
9062 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009063 // If an offer can satisfy the request, it is considered needed if it is currently
9064 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009065 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009066 && satisfier.factorySerialNumber == offer.providerId
9067 && activeRequest.canBeSatisfiedBy(offer.caps);
9068 final boolean newNeeded = currentlyServing
9069 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009070 if (newNeeded != oldNeeded) {
9071 if (newNeeded) {
9072 offer.onNetworkNeeded(activeRequest);
9073 } else {
9074 // The offer used to be able to beat the satisfier. Now it can't.
9075 offer.onNetworkUnneeded(activeRequest);
9076 }
9077 }
9078 }
9079
9080 // Third phase : inform the providers that the offer isn't needed for any request
9081 // below the active one.
9082 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9083 final NetworkRequest request = nri.mRequests.get(i);
9084 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9085 // Since this request is lower-priority than the one currently satisfied, if the
9086 // offer can satisfy it, the provider should not try and bring up the network.
9087 // Hence tell the provider so unless it already knew.
9088 if (offer.neededFor(request)) {
9089 offer.onNetworkUnneeded(request);
9090 }
9091 }
9092 }
9093
Chalard Jean61c79252019-11-07 23:07:32 +09009094 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9095 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9096 NetworkRequest nr = nai.requestAt(i);
9097 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9098 // legacy type tracker filters out repeat adds
9099 mLegacyTypeTracker.add(nr.legacyType, nai);
9100 }
9101 }
9102
9103 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009104 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009105 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9106 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9107 if (nai.isVPN()) {
9108 mLegacyTypeTracker.add(TYPE_VPN, nai);
9109 }
9110 }
9111
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009112 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009113 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009114 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009115 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009116 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009117 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009118
Chalard Jean254bd162022-08-25 13:04:51 +09009119 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009120 // Don't repeat publish.
9121 if (newInetCondition == mDefaultInetConditionPublished) return;
9122
9123 mDefaultInetConditionPublished = newInetCondition;
9124 sendInetConditionBroadcast(nai.networkInfo);
9125 }
9126
Chalard Jeand61375d2020-01-14 22:46:36 +09009127 @NonNull
9128 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9129 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009130 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009131 final boolean suspended =
9132 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9133 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9134 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9135 // state. This is because the network could have been suspended before connecting,
9136 // or it could be disconnecting while being suspended, and in both these cases
9137 // the state should not be overridden. Note that the only detailed state that
9138 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9139 // worry about multiple different substates of CONNECTED.
9140 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9141 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009142 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9143 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9144 // network agent is created, then goes to suspended, then goes out of suspended without
9145 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009146 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009147 ? NetworkInfo.DetailedState.CONNECTED
9148 : NetworkInfo.DetailedState.CONNECTING,
9149 info.getReason(),
9150 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009151 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009152 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009153 return newInfo;
9154 }
9155
9156 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9157 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9158
Erik Kline99f301b2017-02-15 19:59:17 +09009159 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009160 NetworkInfo oldInfo = null;
9161 synchronized (networkAgent) {
9162 oldInfo = networkAgent.networkInfo;
9163 networkAgent.networkInfo = newInfo;
9164 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009165
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009166 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009167 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9168 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009169 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009170
Chalard Jean254bd162022-08-25 13:04:51 +09009171 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009172 && (state == NetworkInfo.State.CONNECTED
9173 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009174
9175 // A network that has just connected has zero requests and is thus a foreground network.
9176 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9177
Luke Huangfdd11f82019-04-09 18:41:49 +08009178 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009179 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009180 // Initialize the network's capabilities to their starting values according to the
9181 // underlying networks. This ensures that the capabilities are correct before
9182 // anything happens to the network.
9183 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009184 }
Chalard Jean254bd162022-08-25 13:04:51 +09009185 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009186 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009187 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Robin Leea8c0b6e2016-05-01 23:00:00 +01009188 }
9189
Chalard Jean254bd162022-08-25 13:04:51 +09009190 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9191 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009192
lucaslin45e639b2019-04-03 17:09:28 +08009193 // NetworkCapabilities need to be set before sending the private DNS config to
9194 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009195 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9196
Erik Kline9a62f012018-03-21 07:18:33 -07009197 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009198 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9199 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009200
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009201 // If a rate limit has been configured and is applicable to this network (network
9202 // provides internet connectivity), apply it. The tc police filter cannot be attached
9203 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9204 // updateInterfaces -> INetd#networkAddInterface.
9205 // Note: in case of a system server crash, the NetworkController constructor in netd
9206 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9207 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9208 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9209 mIngressRateLimit);
9210 }
9211
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009212 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9213 // command must be sent after updating LinkProperties to maximize chances of
9214 // NetworkMonitor seeing the correct LinkProperties when starting.
9215 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009216 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009217 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009218 }
Chalard Jeand4900722022-02-06 12:25:38 +09009219 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9220 params.networkAgentConfig = networkAgent.networkAgentConfig;
9221 params.networkCapabilities = networkAgent.networkCapabilities;
9222 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9223 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009224 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9225 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9226 // call that would cause a Log.wtf to be emitted from the system_server process, and
9227 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9228 // process to check the interface version, just use an SDK check. NetworkStack will
9229 // always be new enough when running on T+.
9230 if (SdkLevel.isAtLeastT()) {
9231 networkAgent.networkMonitor().notifyNetworkConnected(params);
9232 } else {
9233 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9234 params.networkCapabilities);
9235 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09009236 scheduleEvaluationTimeout(networkAgent.network, INITIAL_EVALUATION_TIMEOUT_MS);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009237
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009238 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9239 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9240 // capabilities, so it only needs to be done once on initial connect, not every time the
9241 // network's capabilities change. Note that we do this before rematching the network,
9242 // so we could decide to tear it down immediately afterwards. That's fine though - on
9243 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9244 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009245 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009246
junyulai0ac374f2020-12-14 18:41:52 +08009247 // Before first rematching networks, put an inactivity timer without any request, this
9248 // allows {@code updateInactivityState} to update the state accordingly and prevent
9249 // tearing down for any {@code unneeded} evaluation in this period.
9250 // Note that the timer will not be rescheduled since the expiry time is
9251 // fixed after connection regardless of the network satisfying other requests or not.
9252 // But it will be removed as soon as the network satisfies a request for the first time.
9253 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9254 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009255 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009256
Paul Jensen05e85ee2014-09-11 11:00:39 -04009257 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009258 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009259
9260 // This has to happen after matching the requests, because callbacks are just requests.
9261 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009262 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009263 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009264 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009265 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009266 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009267 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009268 if (networkAgent.isVPN()) {
9269 // As the active or bound network changes for apps, broadcast the default proxy, as
9270 // apps may need to update their proxy data. This is called after disconnecting from
9271 // VPN to make sure we do not broadcast the old proxy data.
9272 // TODO(b/122649188): send the broadcast only to VPN users.
9273 mProxyTracker.sendProxyBroadcast();
9274 }
Chalard Jean254bd162022-08-25 13:04:51 +09009275 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9276 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009277 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009278 }
9279 }
9280
Chalard Jean28018572020-12-21 18:36:52 +09009281 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009282 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9283 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009284 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009285 }
9286
Erik Kline99f301b2017-02-15 19:59:17 +09009287 // Notify only this one new request of the current state. Transfer all the
9288 // current state by calling NetworkCapabilities and LinkProperties callbacks
9289 // so that callers can be guaranteed to have as close to atomicity in state
9290 // transfer as can be supported by this current API.
9291 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009292 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009293 if (nri.mPendingIntent != null) {
9294 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9295 // Attempt no subsequent state pushes where intents are involved.
9296 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009297 }
Erik Kline99f301b2017-02-15 19:59:17 +09009298
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009299 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009300 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009301 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9302 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9303 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009304 }
9305
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009306 // Notify the requests on this NAI that the network is now lingered.
9307 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009308 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009309 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9310 }
9311
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009312 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9313 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9314 return vpnBlocked
9315 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9316 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9317 }
9318
9319 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9320 if (blockedReasons == BLOCKED_REASON_NONE) {
9321 mUidBlockedReasons.delete(uid);
9322 } else {
9323 mUidBlockedReasons.put(uid, blockedReasons);
9324 }
9325 }
9326
junyulaif2c67e42018-08-07 19:50:45 +08009327 /**
9328 * Notify of the blocked state apps with a registered callback matching a given NAI.
9329 *
9330 * Unlike other callbacks, blocked status is different between each individual uid. So for
9331 * any given nai, all requests need to be considered according to the uid who filed it.
9332 *
9333 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009334 * @param oldMetered True if the previous network capabilities were metered.
9335 * @param newMetered True if the current network capabilities are metered.
9336 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9337 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009338 */
9339 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009340 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9341 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009342
9343 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9344 NetworkRequest nr = nai.requestAt(i);
9345 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009346
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009347 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9348 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9349 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009350 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009351 : oldVpnBlocked;
9352
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009353 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9354 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9355 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009356 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009357 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009358 }
9359 }
9360 }
9361
9362 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009363 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009364 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009365 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009366 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009367 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009368 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009369 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009370 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009371
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009372 final int oldBlockedState = getBlockedState(
9373 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9374 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9375 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009376 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009377 }
junyulaif2c67e42018-08-07 19:50:45 +08009378 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9379 NetworkRequest nr = nai.requestAt(i);
9380 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009381 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009382 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9383 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009384 }
9385 }
9386 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009387 }
9388
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009389 @VisibleForTesting
9390 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009391 // The NetworkInfo we actually send out has no bearing on the real
9392 // state of affairs. For example, if the default connection is mobile,
9393 // and a request for HIPRI has just gone away, we need to pretend that
9394 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9395 // the state to DISCONNECTED, even though the network is of type MOBILE
9396 // and is still connected.
9397 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9398 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009399 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009400 if (state != DetailedState.DISCONNECTED) {
9401 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009402 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009403 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009404 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009405 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9406 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9407 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9408 if (info.isFailover()) {
9409 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9410 nai.networkInfo.setFailover(false);
9411 }
9412 if (info.getReason() != null) {
9413 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9414 }
9415 if (info.getExtraInfo() != null) {
9416 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9417 }
9418 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009419 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009420 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009421 if (newDefaultAgent != null) {
9422 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9423 newDefaultAgent.networkInfo);
9424 } else {
9425 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9426 }
9427 }
9428 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9429 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009430 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009431 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009432 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009433 }
9434 }
9435 }
9436
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009437 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009438 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009439 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009440 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009441 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009442 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9443 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009444 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9445 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009446 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009447 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009448 } else {
9449 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9450 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009451 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009452 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009453
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009454 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9455 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9456 }
9457
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009458 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009459 * Returns the list of all interfaces that could be used by network traffic that does not
9460 * explicitly specify a network. This includes the default network, but also all VPNs that are
9461 * currently connected.
9462 *
9463 * Must be called on the handler thread.
9464 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009465 @NonNull
9466 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009467 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009468 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009469 final Set<Integer> activeNetIds = new ArraySet<>();
9470 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9471 if (nri.isBeingSatisfied()) {
9472 activeNetIds.add(nri.getSatisfier().network().netId);
9473 }
9474 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009475 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009476 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009477 defaultNetworks.add(nai.network);
9478 }
9479 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009480 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009481 }
9482
9483 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009484 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9485 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009486 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009487 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009488 ensureRunningOnConnectivityServiceThread();
9489 String activeIface = null;
9490 LinkProperties activeLinkProperties = getActiveLinkProperties();
9491 if (activeLinkProperties != null) {
9492 activeIface = activeLinkProperties.getInterfaceName();
9493 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009494
junyulai2050bed2021-01-23 09:46:34 +08009495 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009496 try {
junyulaide41fc22021-01-22 22:46:01 +08009497 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009498 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009499 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9500 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009501 } catch (Exception ignored) {
9502 }
9503 }
9504
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009505 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009506 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009507 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009508 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009509 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009510
9511 if (!TextUtils.isEmpty(settingUrl)) {
9512 return settingUrl;
9513 }
9514
9515 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009516 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009517 if (!TextUtils.isEmpty(settingUrl)) {
9518 return settingUrl;
9519 }
9520
9521 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009522 }
9523
9524 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009525 public void startNattKeepalive(Network network, int intervalSeconds,
9526 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009527 enforceKeepalivePermission();
9528 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009529 getNetworkAgentInfoForNetwork(network), null /* fd */,
junyulai070f9ff2019-01-16 20:23:34 +08009530 intervalSeconds, cb,
junyulai011b1f12019-01-03 18:50:15 +08009531 srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009532 }
9533
9534 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009535 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +08009536 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
junyulaid05a1922019-01-15 11:32:44 +08009537 String dstAddr) {
Josh Gao461a1222020-06-16 15:58:11 -07009538 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +08009539 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009540 mKeepaliveTracker.startNattKeepalive(
9541 getNetworkAgentInfoForNetwork(network), fd, resourceId,
9542 intervalSeconds, cb,
9543 srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT);
9544 } finally {
9545 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9546 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009547 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9548 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009549 }
9550 }
junyulaid05a1922019-01-15 11:32:44 +08009551 }
9552
9553 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +08009554 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +08009555 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -07009556 try {
9557 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +08009558 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -07009559 mKeepaliveTracker.startTcpKeepalive(
9560 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
9561 } finally {
9562 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
9563 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +08009564 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
9565 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -07009566 }
9567 }
junyulai0835a1e2019-01-08 20:04:33 +08009568 }
9569
9570 @Override
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009571 public void stopKeepalive(Network network, int slot) {
9572 mHandler.sendMessage(mHandler.obtainMessage(
junyulai011b1f12019-01-03 18:50:15 +08009573 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, slot, SocketKeepalive.SUCCESS, network));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009574 }
9575
9576 @Override
Stuart Scottd5463642015-04-02 18:00:02 -07009577 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +08009578 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -07009579
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009580 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +08009581 final long token = Binder.clearCallingIdentity();
9582 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009583 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
9584 UserHandle.getUserHandleForUid(uid))) {
9585 return;
9586 }
9587
Heemin Seogdb8489d2019-06-12 09:21:44 -07009588 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
9589 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +08009590
9591 // Turn airplane mode off
9592 setAirplaneMode(false);
9593
9594 // restore private DNS settings to default mode (opportunistic)
9595 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
9596 UserHandle.getUserHandleForUid(uid))) {
9597 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
9598 PRIVATE_DNS_MODE_OPPORTUNISTIC);
9599 }
9600
9601 Settings.Global.putString(mContext.getContentResolver(),
9602 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +08009603 } finally {
9604 Binder.restoreCallingIdentity(token);
9605 }
Stuart Scottd5463642015-04-02 18:00:02 -07009606 }
Paul Jensen6eb94e62015-07-01 14:16:32 -04009607
Ricky Wai7097cc92018-01-23 04:09:45 +00009608 @Override
9609 public byte[] getNetworkWatchlistConfigHash() {
9610 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
9611 if (nwm == null) {
9612 loge("Unable to get NetworkWatchlistManager");
9613 return null;
9614 }
9615 // Redirect it to network watchlist service to access watchlist file and calculate hash.
9616 return nwm.getWatchlistConfigHash();
9617 }
9618
Hugo Benichibe0c7652016-05-31 16:28:06 +09009619 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +09009620 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -08009621 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +09009622 }
Hugo Benichif4210292017-04-21 15:07:12 +09009623
9624 private static boolean toBool(int encodedBoolean) {
9625 return encodedBoolean != 0; // Only 0 means false.
9626 }
9627
9628 private static int encodeBool(boolean b) {
9629 return b ? 1 : 0;
9630 }
mswest4632928412018-03-12 10:34:34 -07009631
9632 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009633 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
9634 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
9635 @NonNull String[] args) {
9636 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
9637 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -07009638 }
9639
Chiachang Wang77ae8a02020-10-12 15:20:07 +08009640 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -07009641 @Override
9642 public int onCommand(String cmd) {
9643 if (cmd == null) {
9644 return handleDefaultCommands(cmd);
9645 }
9646 final PrintWriter pw = getOutPrintWriter();
9647 try {
9648 switch (cmd) {
9649 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009650 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
9651 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -07009652 final String action = getNextArg();
9653 if ("enable".equals(action)) {
9654 setAirplaneMode(true);
9655 return 0;
9656 } else if ("disable".equals(action)) {
9657 setAirplaneMode(false);
9658 return 0;
9659 } else if (action == null) {
9660 final ContentResolver cr = mContext.getContentResolver();
9661 final int enabled = Settings.Global.getInt(cr,
9662 Settings.Global.AIRPLANE_MODE_ON);
9663 pw.println(enabled == 0 ? "disabled" : "enabled");
9664 return 0;
9665 } else {
9666 onHelp();
9667 return -1;
9668 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +09009669 case "reevaluate":
9670 // Usage : adb shell cmd connectivity reevaluate <netId>
9671 // If netId is omitted, then reevaluate the default network
9672 final String netId = getNextArg();
9673 final NetworkAgentInfo nai;
9674 if (null == netId) {
9675 // Note that the command is running on the wrong thread to call this,
9676 // so this could in principle return stale data. But it can't crash.
9677 nai = getDefaultNetwork();
9678 } else {
9679 // If netId can't be parsed, this throws NumberFormatException, which
9680 // is passed back to adb who prints it.
9681 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
9682 }
9683 if (null == nai) {
9684 pw.println("Unknown network (net ID not found or no default network)");
9685 return 0;
9686 }
9687 Log.d(TAG, "Reevaluating network " + nai.network);
9688 reportNetworkConnectivity(nai.network, !nai.isValidated());
9689 return 0;
mswest4632928412018-03-12 10:34:34 -07009690 default:
9691 return handleDefaultCommands(cmd);
9692 }
9693 } catch (Exception e) {
9694 pw.println(e);
9695 }
9696 return -1;
9697 }
9698
9699 @Override
9700 public void onHelp() {
9701 PrintWriter pw = getOutPrintWriter();
9702 pw.println("Connectivity service commands:");
9703 pw.println(" help");
9704 pw.println(" Print this help text.");
9705 pw.println(" airplane-mode [enable|disable]");
9706 pw.println(" Turn airplane mode on or off.");
9707 pw.println(" airplane-mode");
9708 pw.println(" Get airplane mode.");
9709 }
9710 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009711
Remi NGUYEN VAN06830742021-03-06 00:11:24 +09009712 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009713 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
9714 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
9715 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +08009716 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009717 }
9718
he_won.hwang881307a2022-03-15 21:23:52 +09009719 private void maybeUpdateWifiRoamTimestamp(NetworkAgentInfo nai, NetworkCapabilities nc) {
9720 if (nai == null) return;
9721 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
9722 final TransportInfo newInfo = nc.getTransportInfo();
9723 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
9724 return;
9725 }
9726 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +09009727 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +09009728 }
9729 }
9730
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009731 /**
9732 * @param connectionInfo the connection to resolve.
9733 * @return {@code uid} if the connection is found and the app has permission to observe it
9734 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
9735 * connection is not found.
9736 */
9737 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009738 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
9739 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
9740 }
9741
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09009742 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009743 connectionInfo.local, connectionInfo.remote);
9744
Lorenzo Colittia5a903d2021-02-04 00:18:27 +09009745 if (uid == INVALID_UID) return uid; // Not found.
9746
9747 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
9748 // VPN, if any, that applies to the UID that owns the connection.
9749 if (checkNetworkStackPermission()) return uid;
9750
9751 final NetworkAgentInfo vpn = getVpnForUid(uid);
9752 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09009753 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07009754 return INVALID_UID;
9755 }
9756
9757 return uid;
9758 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +00009759
Benedict Wong493e04b2018-11-09 14:45:34 -08009760 /**
9761 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
9762 *
9763 * <p>The TestNetworkService must be run in the system server due to TUN creation.
9764 */
9765 @Override
9766 public IBinder startOrGetTestNetworkService() {
9767 synchronized (mTNSLock) {
9768 TestNetworkService.enforceTestNetworkPermissions(mContext);
9769
9770 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +08009771 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -08009772 }
9773
9774 return mTNS;
9775 }
9776 }
Cody Kestingd199a9d2019-12-17 12:55:28 -08009777
Cody Kesting73708bf2019-12-18 10:57:50 -08009778 /**
9779 * Handler used for managing all Connectivity Diagnostics related functions.
9780 *
9781 * @see android.net.ConnectivityDiagnosticsManager
9782 *
9783 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
9784 */
9785 @VisibleForTesting
9786 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009787 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
9788
Cody Kesting73708bf2019-12-18 10:57:50 -08009789 /**
9790 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
9791 * android.net.ConnectivityDiagnosticsManager}.
9792 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
9793 * NetworkRequestInfo to be registered
9794 */
9795 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
9796
9797 /**
9798 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
9799 * android.net.ConnectivityDiagnosticsManager}.
9800 * obj = the IConnectivityDiagnosticsCallback to be unregistered
9801 * arg1 = the uid of the caller
9802 */
9803 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
9804
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009805 /**
9806 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009807 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009808 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
9809 * NetworkMonitor.
9810 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009811 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009812 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009813
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009814 /**
9815 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
9816 * been detected on the network.
9817 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
9818 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
9819 * arg2 = NetID.
9820 * data = PersistableBundle of extras passed from NetworkMonitor.
9821 */
9822 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
9823
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009824 /**
9825 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
9826 * the platform. This event will invoke {@link
9827 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
9828 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -07009829 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009830 */
9831 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
9832
Cody Kesting73708bf2019-12-18 10:57:50 -08009833 private ConnectivityDiagnosticsHandler(Looper looper) {
9834 super(looper);
9835 }
9836
9837 @Override
9838 public void handleMessage(Message msg) {
9839 switch (msg.what) {
9840 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9841 handleRegisterConnectivityDiagnosticsCallback(
9842 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
9843 break;
9844 }
9845 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
9846 handleUnregisterConnectivityDiagnosticsCallback(
9847 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
9848 break;
9849 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09009850 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009851 final ConnectivityReportEvent reportEvent =
9852 (ConnectivityReportEvent) msg.obj;
9853
Aaron Huang959d3642021-01-21 15:47:41 +08009854 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009855 break;
9856 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009857 case EVENT_DATA_STALL_SUSPECTED: {
9858 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +08009859 final Pair<Long, PersistableBundle> arg =
9860 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009861 if (nai == null) break;
9862
Aaron Huang959d3642021-01-21 15:47:41 +08009863 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08009864 break;
9865 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009866 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -07009867 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08009868 break;
9869 }
9870 default: {
9871 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
9872 }
Cody Kesting73708bf2019-12-18 10:57:50 -08009873 }
9874 }
9875 }
9876
9877 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
9878 @VisibleForTesting
9879 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
9880 @NonNull private final IConnectivityDiagnosticsCallback mCb;
9881 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009882 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009883
9884 @VisibleForTesting
9885 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009886 @NonNull IConnectivityDiagnosticsCallback cb,
9887 @NonNull NetworkRequestInfo nri,
9888 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009889 mCb = cb;
9890 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009891 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -08009892 }
9893
9894 @Override
9895 public void binderDied() {
9896 log("ConnectivityDiagnosticsCallback IBinder died.");
9897 unregisterConnectivityDiagnosticsCallback(mCb);
9898 }
9899 }
9900
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009901 /**
9902 * Class used for sending information from {@link
9903 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
9904 */
9905 private static class NetworkTestedResults {
9906 private final int mNetId;
9907 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009908 @Nullable private final String mRedirectUrl;
9909
9910 private NetworkTestedResults(
9911 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
9912 mNetId = netId;
9913 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009914 mRedirectUrl = redirectUrl;
9915 }
9916 }
9917
9918 /**
9919 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
9920 * ConnectivityDiagnosticsHandler}.
9921 */
9922 private static class ConnectivityReportEvent {
9923 private final long mTimestampMillis;
9924 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +08009925 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009926
Aaron Huang959d3642021-01-21 15:47:41 +08009927 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
9928 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009929 mTimestampMillis = timestampMillis;
9930 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +08009931 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -08009932 }
9933 }
9934
Cody Kestingf1120be2020-08-03 18:01:40 -07009935 /**
9936 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
9937 * ConnectivityDiagnosticsHandler}.
9938 */
9939 private static class ReportedNetworkConnectivityInfo {
9940 public final boolean hasConnectivity;
9941 public final boolean isNetworkRevalidating;
9942 public final int reporterUid;
9943 @NonNull public final NetworkAgentInfo nai;
9944
9945 private ReportedNetworkConnectivityInfo(
9946 boolean hasConnectivity,
9947 boolean isNetworkRevalidating,
9948 int reporterUid,
9949 @NonNull NetworkAgentInfo nai) {
9950 this.hasConnectivity = hasConnectivity;
9951 this.isNetworkRevalidating = isNetworkRevalidating;
9952 this.reporterUid = reporterUid;
9953 this.nai = nai;
9954 }
9955 }
9956
Cody Kesting73708bf2019-12-18 10:57:50 -08009957 private void handleRegisterConnectivityDiagnosticsCallback(
9958 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
9959 ensureRunningOnConnectivityServiceThread();
9960
9961 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -08009962 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -08009963 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
9964
James Mattis64b8b0f2020-11-24 17:40:49 -08009965 // Connectivity Diagnostics are meant to be used with a single network request. It would be
9966 // confusing for these networks to change when an NRI is satisfied in another layer.
9967 if (nri.isMultilayerRequest()) {
9968 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
9969 + "network requests.");
9970 }
9971
Cody Kesting73708bf2019-12-18 10:57:50 -08009972 // This means that the client registered the same callback multiple times. Do
9973 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -08009974 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009975 if (VDBG) log("Diagnostics callback is already registered");
9976
9977 // Decrement the reference count for this NetworkRequestInfo. The reference count is
9978 // incremented when the NetworkRequestInfo is created as part of
9979 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +08009980 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -08009981 return;
9982 }
9983
Cody Kesting31f1ff62020-03-05 10:46:02 -08009984 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -08009985
9986 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -08009987 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -08009988 } catch (RemoteException e) {
9989 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -08009990 return;
9991 }
9992
9993 // Once registered, provide ConnectivityReports for matching Networks
9994 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
9995 synchronized (mNetworkForNetId) {
9996 for (int i = 0; i < mNetworkForNetId.size(); i++) {
9997 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -08009998 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
9999 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010000 matchingNetworks.add(nai);
10001 }
10002 }
10003 }
10004 for (final NetworkAgentInfo nai : matchingNetworks) {
10005 final ConnectivityReport report = nai.getConnectivityReport();
10006 if (report == null) {
10007 continue;
10008 }
10009 if (!checkConnectivityDiagnosticsPermissions(
10010 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10011 continue;
10012 }
10013
10014 try {
10015 cb.onConnectivityReportAvailable(report);
10016 } catch (RemoteException e) {
10017 // Exception while sending the ConnectivityReport. Move on to the next network.
10018 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010019 }
10020 }
10021
10022 private void handleUnregisterConnectivityDiagnosticsCallback(
10023 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10024 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010025 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010026
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010027 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10028 mConnectivityDiagnosticsCallbacks.remove(iCb);
10029 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010030 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10031 return;
10032 }
10033
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010034 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010035
Cody Kesting70fa2b22020-12-02 12:16:56 -080010036 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10037 // (if the Binder died)
10038 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10039 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010040 return;
10041 }
10042
Cody Kesting46cb1672020-03-04 13:35:20 -080010043 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10044 // incremented when the NetworkRequestInfo is created as part of
10045 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010046 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010047
Cody Kesting31f1ff62020-03-05 10:46:02 -080010048 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010049 }
10050
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010051 private void handleNetworkTestedWithExtras(
10052 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10053 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010054 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010055 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010056 final ConnectivityReport report =
10057 new ConnectivityReport(
10058 reportEvent.mNai.network,
10059 reportEvent.mTimestampMillis,
10060 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010061 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010062 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010063 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010064
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010065 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010066 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010067 for (final IConnectivityDiagnosticsCallback cb : results) {
10068 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010069 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010070 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010071 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010072 }
10073 }
10074 }
10075
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010076 private void handleDataStallSuspected(
10077 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10078 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010079 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010080 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010081 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010082 new DataStallReport(
10083 nai.network,
10084 timestampMillis,
10085 detectionMethod,
10086 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010087 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010088 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010089 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010090 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010091 for (final IConnectivityDiagnosticsCallback cb : results) {
10092 try {
10093 cb.onDataStallSuspected(report);
10094 } catch (RemoteException ex) {
10095 loge("Error invoking onDataStallSuspected", ex);
10096 }
10097 }
10098 }
10099
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010100 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010101 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10102 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10103 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10104
10105 // If the Network is being re-validated as a result of this call to
10106 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10107 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010108 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010109 getMatchingPermissionedCallbacks(
10110 nai,
10111 reportedNetworkConnectivityInfo.isNetworkRevalidating
10112 ? Process.INVALID_UID
10113 : reportedNetworkConnectivityInfo.reporterUid);
10114
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010115 for (final IConnectivityDiagnosticsCallback cb : results) {
10116 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010117 cb.onNetworkConnectivityReported(
10118 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010119 } catch (RemoteException ex) {
10120 loge("Error invoking onNetworkConnectivityReported", ex);
10121 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010122
10123 // If the Network isn't re-validating, also provide the cached report. If there is no
10124 // cached report, the Network is still being validated and a report will be sent once
10125 // validation is complete. Note that networks which never undergo validation will still
10126 // have a cached ConnectivityReport with RESULT_SKIPPED.
10127 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10128 try {
10129 cb.onConnectivityReportAvailable(cachedReport);
10130 } catch (RemoteException ex) {
10131 loge("Error invoking onConnectivityReportAvailable", ex);
10132 }
10133 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010134 }
10135 }
10136
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010137 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010138 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10139 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010140 sanitized.setUids(null);
10141 sanitized.setAdministratorUids(new int[0]);
10142 sanitized.setOwnerUid(Process.INVALID_UID);
10143 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010144 }
10145
Cody Kestingf1120be2020-08-03 18:01:40 -070010146 /**
10147 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10148 *
10149 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10150 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010151 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010152 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010153 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010154 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010155 mConnectivityDiagnosticsCallbacks.entrySet()) {
10156 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10157 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010158
James Mattis64b8b0f2020-11-24 17:40:49 -080010159 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010160 if (!nai.satisfies(nri.mRequests.get(0))) {
10161 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010162 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010163
10164 // UID for this callback must either be:
10165 // - INVALID_UID (which sends callbacks to all UIDs), or
10166 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10167 // notified as a result)
10168 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10169 continue;
10170 }
10171
10172 if (!checkConnectivityDiagnosticsPermissions(
10173 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10174 continue;
10175 }
10176
10177 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010178 }
10179 return results;
10180 }
10181
Cody Kesting7474f672021-05-11 14:22:40 -070010182 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10183 @NonNull NetworkAgentInfo nai) {
10184 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10185 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10186 }
10187
Cody Kesting160ef392021-05-05 13:17:22 -070010188 private boolean hasLocationPermission(String packageName, int uid) {
10189 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10190 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10191 // call in a try-catch.
10192 try {
10193 if (!mLocationPermissionChecker.checkLocationPermission(
10194 packageName, null /* featureId */, uid, null /* message */)) {
10195 return false;
10196 }
10197 } catch (SecurityException e) {
10198 return false;
10199 }
10200
10201 return true;
10202 }
10203
10204 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10205 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010206 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010207 && virtual.networkCapabilities.getOwnerUid() == uid
10208 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10209 return true;
10210 }
10211 }
10212
10213 return false;
10214 }
10215
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010216 @VisibleForTesting
10217 boolean checkConnectivityDiagnosticsPermissions(
10218 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10219 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10220 return true;
10221 }
10222
Cody Kesting160ef392021-05-05 13:17:22 -070010223 // Administrator UIDs also contains the Owner UID
10224 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10225 if (!CollectionUtils.contains(administratorUids, callbackUid)
10226 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010227 return false;
10228 }
10229
Cody Kesting7474f672021-05-11 14:22:40 -070010230 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10231 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010232 }
10233
Cody Kestingd199a9d2019-12-17 12:55:28 -080010234 @Override
10235 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010236 @NonNull IConnectivityDiagnosticsCallback callback,
10237 @NonNull NetworkRequest request,
10238 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010239 Objects.requireNonNull(callback, "callback must not be null");
10240 Objects.requireNonNull(request, "request must not be null");
10241 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10242
Cody Kesting73708bf2019-12-18 10:57:50 -080010243 if (request.legacyType != TYPE_NONE) {
10244 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10245 + " Please use NetworkCapabilities instead.");
10246 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010247 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010248 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010249
10250 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10251 // and administrator uids to be safe.
10252 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010253 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010254
10255 final NetworkRequest requestWithId =
10256 new NetworkRequest(
10257 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10258
10259 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10260 //
10261 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10262 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10263 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010264 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010265 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010266 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010267
10268 mConnectivityDiagnosticsHandler.sendMessage(
10269 mConnectivityDiagnosticsHandler.obtainMessage(
10270 ConnectivityDiagnosticsHandler
10271 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10272 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010273 }
10274
10275 @Override
10276 public void unregisterConnectivityDiagnosticsCallback(
10277 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010278 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010279 mConnectivityDiagnosticsHandler.sendMessage(
10280 mConnectivityDiagnosticsHandler.obtainMessage(
10281 ConnectivityDiagnosticsHandler
10282 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010283 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010284 0,
10285 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010286 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010287
10288 @Override
10289 public void simulateDataStall(int detectionMethod, long timestampMillis,
10290 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010291 Objects.requireNonNull(network, "network must not be null");
10292 Objects.requireNonNull(extras, "extras must not be null");
10293
paulhu3ffffe72021-09-16 10:15:22 +080010294 enforceAnyPermissionOf(mContext,
10295 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010296 android.Manifest.permission.NETWORK_STACK);
10297 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
10298 if (!nc.hasTransport(TRANSPORT_TEST)) {
Chalard Jean15228572022-01-28 19:29:12 +090010299 throw new SecurityException("Data Stall simulation is only possible for test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010300 }
10301
10302 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010303 if (nai == null || nai.creatorUid != mDeps.getCallingUid()) {
Cody Kestingf53a0752020-04-15 12:33:28 -070010304 throw new SecurityException("Data Stall simulation is only possible for network "
10305 + "creators");
10306 }
10307
Cody Kesting652e3ec2020-05-21 12:08:21 -070010308 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10309 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10310 // Data Stall information as a DataStallReportParcelable and passing to
10311 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10312 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010313 final DataStallReportParcelable p = new DataStallReportParcelable();
10314 p.timestampMillis = timestampMillis;
10315 p.detectionMethod = detectionMethod;
10316
10317 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10318 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10319 }
10320 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10321 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10322 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10323 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10324 }
10325
Serik Beketayevec8ad212020-12-07 22:43:07 -080010326 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010327 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010328
lucaslin66f44212021-02-23 01:12:55 +080010329 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10330 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010331 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010332 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010333 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010334 }
lucaslin37a16d92021-01-21 19:48:09 +080010335
10336 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010337 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010338 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010339 nai.clatd.interfaceLinkStateChanged(iface, up);
10340 }
10341 }
10342
10343 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010344 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010345 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010346 nai.clatd.interfaceRemoved(iface);
10347 }
lucaslin66f44212021-02-23 01:12:55 +080010348 }
10349 }
10350
lucaslin1a8b4c62021-01-21 02:02:55 +080010351 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10352
10353 /**
10354 * Class used for updating network activity tracking with netd and notify network activity
10355 * changes.
10356 */
10357 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010358 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010359 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010360 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010361 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10362 new RemoteCallbackList<>();
10363 // Indicate the current system default network activity is active or not.
10364 @GuardedBy("mActiveIdleTimers")
10365 private boolean mNetworkActive;
10366 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010367 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010368 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010369
Chalard Jean46bfbf02022-02-02 00:56:25 +090010370 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010371 public final int timeout;
10372 public final int transportType;
10373
10374 IdleTimerParams(int timeout, int transport) {
10375 this.timeout = timeout;
10376 this.transportType = transport;
10377 }
10378 }
10379
10380 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010381 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010382 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010383 mNetd = netd;
10384 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010385 }
10386
lucaslin66f44212021-02-23 01:12:55 +080010387 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10388 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10389 synchronized (mActiveIdleTimers) {
10390 mNetworkActive = active;
10391 // If there are no idle timers, it means that system is not monitoring
10392 // activity, so the system default network for those default network
10393 // unspecified apps is always considered active.
10394 //
10395 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10396 // any network activity change event. Whenever this event is received,
10397 // the mActiveIdleTimers should be always not empty. The legacy behavior
10398 // is no-op. Remove to refer to mNetworkActive only.
10399 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10400 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10401 }
10402 }
10403 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010404
lucaslin1193a5d2021-01-21 02:04:15 +080010405 // The network activity should only be updated from ConnectivityService handler thread
10406 // when mActiveIdleTimers lock is held.
10407 @GuardedBy("mActiveIdleTimers")
10408 private void reportNetworkActive() {
10409 final int length = mNetworkActivityListeners.beginBroadcast();
10410 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10411 try {
10412 for (int i = 0; i < length; i++) {
10413 try {
10414 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10415 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010416 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010417 }
10418 }
10419 } finally {
10420 mNetworkActivityListeners.finishBroadcast();
10421 }
10422 }
10423
10424 @GuardedBy("mActiveIdleTimers")
10425 public void handleReportNetworkActivity() {
10426 synchronized (mActiveIdleTimers) {
10427 reportNetworkActive();
10428 }
10429 }
10430
lucaslin1a8b4c62021-01-21 02:02:55 +080010431 // This is deprecated and only to support legacy use cases.
10432 private int transportTypeToLegacyType(int type) {
10433 switch (type) {
10434 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010435 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010436 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010437 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010438 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010439 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010440 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010441 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010442 default:
10443 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10444 }
10445 return ConnectivityManager.TYPE_NONE;
10446 }
10447
10448 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10449 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10450 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10451 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10452 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10453 final long ident = Binder.clearCallingIdentity();
10454 try {
10455 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10456 RECEIVE_DATA_ACTIVITY_CHANGE,
10457 null /* resultReceiver */,
10458 null /* scheduler */,
10459 0 /* initialCode */,
10460 null /* initialData */,
10461 null /* initialExtra */);
10462 } finally {
10463 Binder.restoreCallingIdentity(ident);
10464 }
10465 }
10466
10467 /**
10468 * Setup data activity tracking for the given network.
10469 *
10470 * Every {@code setupDataActivityTracking} should be paired with a
10471 * {@link #removeDataActivityTracking} for cleanup.
10472 */
10473 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10474 final String iface = networkAgent.linkProperties.getInterfaceName();
10475
10476 final int timeout;
10477 final int type;
10478
10479 if (networkAgent.networkCapabilities.hasTransport(
10480 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10481 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010482 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010483 10);
10484 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10485 } else if (networkAgent.networkCapabilities.hasTransport(
10486 NetworkCapabilities.TRANSPORT_WIFI)) {
10487 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010488 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010489 15);
10490 type = NetworkCapabilities.TRANSPORT_WIFI;
10491 } else {
10492 return; // do not track any other networks
10493 }
10494
lucaslinb961efc2021-01-21 02:03:17 +080010495 updateRadioPowerState(true /* isActive */, type);
10496
lucaslin1a8b4c62021-01-21 02:02:55 +080010497 if (timeout > 0 && iface != null) {
10498 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010499 synchronized (mActiveIdleTimers) {
10500 // Networks start up.
10501 mNetworkActive = true;
10502 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10503 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10504 reportNetworkActive();
10505 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010506 } catch (Exception e) {
10507 // You shall not crash!
10508 loge("Exception in setupDataActivityTracking " + e);
10509 }
10510 }
10511 }
10512
10513 /**
10514 * Remove data activity tracking when network disconnects.
10515 */
10516 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
10517 final String iface = networkAgent.linkProperties.getInterfaceName();
10518 final NetworkCapabilities caps = networkAgent.networkCapabilities;
10519
lucaslinb961efc2021-01-21 02:03:17 +080010520 if (iface == null) return;
10521
10522 final int type;
10523 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
10524 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10525 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
10526 type = NetworkCapabilities.TRANSPORT_WIFI;
10527 } else {
10528 return; // do not track any other networks
10529 }
10530
10531 try {
10532 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080010533 synchronized (mActiveIdleTimers) {
10534 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
10535 // The call fails silently if no idle timer setup for this interface
10536 mNetd.idletimerRemoveInterface(iface, params.timeout,
10537 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080010538 }
lucaslinb961efc2021-01-21 02:03:17 +080010539 } catch (Exception e) {
10540 // You shall not crash!
10541 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080010542 }
10543 }
10544
10545 /**
10546 * Update data activity tracking when network state is updated.
10547 */
10548 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
10549 NetworkAgentInfo oldNetwork) {
10550 if (newNetwork != null) {
10551 setupDataActivityTracking(newNetwork);
10552 }
10553 if (oldNetwork != null) {
10554 removeDataActivityTracking(oldNetwork);
10555 }
10556 }
lucaslinb961efc2021-01-21 02:03:17 +080010557
10558 private void updateRadioPowerState(boolean isActive, int transportType) {
10559 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
10560 switch (transportType) {
10561 case NetworkCapabilities.TRANSPORT_CELLULAR:
10562 bs.reportMobileRadioPowerState(isActive, NO_UID);
10563 break;
10564 case NetworkCapabilities.TRANSPORT_WIFI:
10565 bs.reportWifiRadioPowerState(isActive, NO_UID);
10566 break;
10567 default:
10568 logw("Untracked transport type:" + transportType);
10569 }
10570 }
lucaslin1193a5d2021-01-21 02:04:15 +080010571
10572 public boolean isDefaultNetworkActive() {
10573 synchronized (mActiveIdleTimers) {
10574 // If there are no idle timers, it means that system is not monitoring activity,
10575 // so the default network is always considered active.
10576 //
10577 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
10578 // tracking is disabled (negative idle timer value configured), or no active default
10579 // network. In the latter case, this reports active but it should report inactive.
10580 return mNetworkActive || mActiveIdleTimers.isEmpty();
10581 }
10582 }
10583
10584 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
10585 mNetworkActivityListeners.register(l);
10586 }
10587
10588 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
10589 mNetworkActivityListeners.unregister(l);
10590 }
lucaslin012f7a12021-01-21 02:04:35 +080010591
10592 public void dump(IndentingPrintWriter pw) {
10593 synchronized (mActiveIdleTimers) {
10594 pw.print("mNetworkActive="); pw.println(mNetworkActive);
10595 pw.println("Idle timers:");
10596 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
10597 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
10598 final IdleTimerParams params = ent.getValue();
10599 pw.print(" timeout="); pw.print(params.timeout);
10600 pw.print(" type="); pw.println(params.transportType);
10601 }
10602 }
10603 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010604 }
James Mattis47db0582021-01-01 14:13:35 -080010605
Daniel Brightf9e945b2020-06-15 16:10:01 -070010606 /**
10607 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
10608 *
10609 * @param socketInfo the socket information
10610 * @param callback the callback to register
10611 */
10612 @Override
10613 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
10614 @NonNull final IQosCallback callback) {
10615 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
10616 if (nai == null || nai.networkCapabilities == null) {
10617 try {
10618 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
10619 } catch (final RemoteException ex) {
10620 loge("registerQosCallbackInternal: RemoteException", ex);
10621 }
10622 return;
10623 }
10624 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
10625 }
10626
10627 /**
10628 * Register a {@link IQosCallback} with base {@link QosFilter}.
10629 *
10630 * @param filter the filter to register
10631 * @param callback the callback to register
10632 * @param nai the agent information related to the filter's network
10633 */
10634 @VisibleForTesting
10635 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
10636 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010637 Objects.requireNonNull(filter, "filter must be non-null");
10638 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010639
10640 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080010641 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
10642 // on this network is unregistered when the app loses permission or b) no QoS
10643 // callbacks are sent for restricted networks unless the app currently has permission
10644 // to access restricted networks.
10645 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070010646 }
10647 mQosCallbackTracker.registerCallback(callback, filter, nai);
10648 }
10649
10650 /**
10651 * Unregisters the given callback.
10652 *
10653 * @param callback the callback to unregister
10654 */
10655 @Override
10656 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010657 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070010658 mQosCallbackTracker.unregisterCallback(callback);
10659 }
James Mattis47db0582021-01-01 14:13:35 -080010660
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010661 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
10662 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
10663 // Enterprise device can be fully managed like device owner and such use case
10664 // also should be supported. Calling app check for work profile and fully managed device
10665 // is already done in DevicePolicyManager.
10666 // This check is an extra caution to be sure device is fully managed or not.
10667 final UserManager um = mContext.getSystemService(UserManager.class);
10668 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
10669 if (um.isManagedProfile(profile.getIdentifier())) {
10670 return true;
10671 }
10672 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
10673 return false;
10674 }
10675
James Mattis45d81842021-01-10 14:24:24 -080010676 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010677 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010678 *
10679 * See the documentation for the individual preferences for a description of the supported
10680 * behaviors.
10681 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010682 * @param profile If the device owner is set, any profile is allowed.
10683 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010684 * @param preferences the list of profile network preferences for the
10685 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090010686 * @param listener an optional listener to listen for completion of the operation.
10687 */
10688 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010689 public void setProfileNetworkPreferences(
10690 @NonNull final UserHandle profile,
10691 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090010692 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010693 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010694 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010695
10696 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010697 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
10698 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
10699 .build();
10700 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010701 }
10702
paulhu3ffffe72021-09-16 10:15:22 +080010703 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010704 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010705 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010706 }
10707 if (profile.getIdentifier() < 0) {
10708 throw new IllegalArgumentException("Must explicitly specify a user handle ("
10709 + "UserHandle.CURRENT not supported)");
10710 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070010711 if (!isNetworkPreferenceAllowedForProfile(profile)) {
10712 throw new IllegalArgumentException("Profile must be a managed profile "
10713 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010714 }
paulhuaa0743d2021-05-26 21:56:03 +080010715
Chalard Jean46bfbf02022-02-02 00:56:25 +090010716 final List<ProfileNetworkPreferenceList.Preference> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010717 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010718 for (final ProfileNetworkPreference preference : preferences) {
10719 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010720 boolean allowFallback = true;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010721 switch (preference.getPreference()) {
10722 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
10723 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010724 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010725 if (preference.getPreferenceEnterpriseId() != 0) {
10726 throw new IllegalArgumentException(
10727 "Invalid enterprise identifier in setProfileNetworkPreferences");
10728 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010729 break;
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010730 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
10731 allowFallback = false;
10732 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010733 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010734 // This code is needed even though there is a check later on,
10735 // because isRangeAlreadyInPreferenceList assumes that every preference
10736 // has a UID list.
10737 if (hasDefaultPreference) {
10738 throw new IllegalArgumentException(
10739 "Default profile preference should not be set along with other "
10740 + "preference");
10741 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010742 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
10743 throw new IllegalArgumentException(
10744 "Invalid enterprise identifier in setProfileNetworkPreferences");
10745 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010746 final Set<UidRange> uidRangeSet =
10747 getUidListToBeAppliedForNetworkPreference(profile, preference);
10748 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
10749 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
10750 } else {
10751 throw new IllegalArgumentException(
10752 "Overlapping uid range in setProfileNetworkPreferences");
10753 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010754 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010755 nc.addEnterpriseId(
10756 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010757 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
10758 break;
10759 default:
10760 throw new IllegalArgumentException(
10761 "Invalid preference in setProfileNetworkPreferences");
10762 }
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010763 preferenceList.add(new ProfileNetworkPreferenceList.Preference(
10764 profile, nc, allowFallback));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010765 if (hasDefaultPreference && preferenceList.size() > 1) {
10766 throw new IllegalArgumentException(
10767 "Default profile preference should not be set along with other preference");
10768 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010769 }
10770 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010771 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010772 }
10773
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010774 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
10775 @NonNull final UserHandle profile,
10776 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
10777 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080010778 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
10779 profileNetworkPreference.getIncludedUids());
10780
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010781 if (uidRangeSet.size() > 0) {
10782 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
10783 throw new IllegalArgumentException(
10784 "Allow uid range is outside the uid range of profile.");
10785 }
10786 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080010787 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010788 profileNetworkPreference.getExcludedUids());
10789 if (disallowUidRangeSet.size() > 0) {
10790 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
10791 throw new IllegalArgumentException(
10792 "disallow uid range is outside the uid range of profile.");
10793 }
10794 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
10795 disallowUidRangeSet);
10796 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010797 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010798 uidRangeSet.add(profileUids);
10799 }
10800 }
10801 return uidRangeSet;
10802 }
10803
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010804 private boolean isEnterpriseIdentifierValid(
10805 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010806 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080010807 return true;
10808 }
10809 return false;
10810 }
10811
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010812 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010813 @NonNull final ProfileNetworkPreferenceList prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010814 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010815 for (final ProfileNetworkPreferenceList.Preference pref : prefs.preferences) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010816 // The NRI for a user should contain the request for capabilities.
10817 // If fallback to default network is needed then NRI should include
10818 // the request for the default network. Create an image of it to
10819 // have the correct UIDs in it (also a request can only be part of one NRI, because
10820 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010821 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
10822 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080010823 if (pref.allowFallback) {
10824 nrs.add(createDefaultInternetRequestForTransport(
10825 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10826 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010827 if (VDBG) {
10828 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
10829 pref.capabilities.getUids()));
10830 }
10831
Chiachang Wang8156c4e2021-03-19 00:45:39 +000010832 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080010833 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080010834 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010835 result.add(nri);
10836 }
10837 return result;
10838 }
10839
Sooraj Sasindran499117f2021-11-29 12:40:09 -080010840 /**
10841 * Compare if the given UID range sets have the same UIDs.
10842 *
10843 */
10844 private boolean isRangeAlreadyInPreferenceList(
10845 @NonNull List<ProfileNetworkPreferenceList.Preference> preferenceList,
10846 @NonNull Set<UidRange> uidRangeSet) {
10847 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
10848 return false;
10849 }
10850 for (ProfileNetworkPreferenceList.Preference pref : preferenceList) {
10851 if (UidRangeUtils.doesRangeSetOverlap(
10852 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
10853 return true;
10854 }
10855 }
10856 return false;
10857 }
10858
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010859 private void handleSetProfileNetworkPreference(
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010860 @NonNull final List<ProfileNetworkPreferenceList.Preference> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010861 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010862 /*
10863 * handleSetProfileNetworkPreference is always called for single user.
10864 * preferenceList only contains preferences for different uids within the same user
10865 * (enforced by getUidListToBeAppliedForNetworkPreference).
10866 * Clear all the existing preferences for the user before applying new preferences.
10867 *
10868 */
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070010869 mProfileNetworkPreferences = mProfileNetworkPreferences.withoutUser(
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010870 preferenceList.get(0).user);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010871 for (final ProfileNetworkPreferenceList.Preference preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080010872 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
10873 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070010874
paulhu74128522021-09-28 02:29:03 +000010875 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
10876 addPerAppDefaultNetworkRequests(
10877 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai31d38bf2022-07-04 17:28:39 +080010878
Chalard Jeanb5a139f2021-02-25 21:46:34 +090010879 // Finally, rematch.
10880 rematchAllNetworksAndRequests();
10881
10882 if (null != listener) {
10883 try {
10884 listener.onComplete();
10885 } catch (RemoteException e) {
10886 loge("Listener for setProfileNetworkPreference has died");
10887 }
10888 }
10889 }
10890
paulhu51f77dc2021-06-07 02:34:20 +000010891 @VisibleForTesting
10892 @NonNull
10893 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
10894 @NonNull final Set<Integer> uids) {
10895 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
10896 if (uids.size() == 0) {
10897 // Should not create NetworkRequestInfo if no preferences. Without uid range in
10898 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
10899 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
10900 return nris;
10901 }
10902
10903 final List<NetworkRequest> requests = new ArrayList<>();
10904 // The NRI should be comprised of two layers:
10905 // - The request for the mobile network preferred.
10906 // - The request for the default network, for fallback.
10907 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090010908 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000010909 requests.add(createDefaultInternetRequestForTransport(
10910 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
10911 final Set<UidRange> ranges = new ArraySet<>();
10912 for (final int uid : uids) {
10913 ranges.add(new UidRange(uid, uid));
10914 }
10915 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080010916 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080010917 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000010918 return nris;
10919 }
10920
10921 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000010922 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000010923 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
10924 addPerAppDefaultNetworkRequests(
10925 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000010926 // Finally, rematch.
10927 rematchAllNetworksAndRequests();
10928 }
10929
Patrick Rohr2857ac42022-01-21 14:58:16 +010010930 private void handleIngressRateLimitChanged() {
10931 final long oldIngressRateLimit = mIngressRateLimit;
10932 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
10933 mContext);
10934 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
10935 if (canNetworkBeRateLimited(networkAgent)) {
10936 // If rate limit has previously been enabled, remove the old limit first.
10937 if (oldIngressRateLimit >= 0) {
10938 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
10939 }
10940 if (mIngressRateLimit >= 0) {
10941 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10942 mIngressRateLimit);
10943 }
10944 }
10945 }
10946 }
10947
10948 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090010949 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
10950 if (!SdkLevel.isAtLeastT()) return false;
10951
Patrick Rohrff3b3f82022-02-09 15:15:52 +010010952 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
10953 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
10954 // internet connectivity can be rate limited.
10955 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
10956 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010010957 return false;
10958 }
10959
10960 final String iface = networkAgent.linkProperties.getInterfaceName();
10961 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010010962 // This may happen in tests, but if there is no interface then there is nothing that
10963 // can be rate limited.
10964 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010010965 return false;
10966 }
10967 return true;
10968 }
10969
James Mattis45d81842021-01-10 14:24:24 -080010970 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080010971 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
10972 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080010973 }
10974
10975 /**
10976 * Used by automotive devices to set the network preferences used to direct traffic at an
10977 * application level as per the given OemNetworkPreferences. An example use-case would be an
10978 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
10979 * vehicle via a particular network.
10980 *
10981 * Calling this will overwrite the existing preference.
10982 *
James Mattisda32cfe2021-01-26 16:23:52 -080010983 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090010984 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080010985 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080010986 */
James Mattis47db0582021-01-01 14:13:35 -080010987 @Override
James Mattis45d81842021-01-10 14:24:24 -080010988 public void setOemNetworkPreference(
10989 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090010990 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080010991
James Mattisfa270db2021-05-31 17:11:10 -070010992 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
10993 // Only bypass the permission/device checks if this is a valid test request.
10994 if (isValidTestOemNetworkPreference(preference)) {
10995 enforceManageTestNetworksPermission();
10996 } else {
10997 enforceAutomotiveDevice();
10998 enforceOemNetworkPreferencesPermission();
10999 validateOemNetworkPreferences(preference);
11000 }
James Mattis45d81842021-01-10 14:24:24 -080011001
James Mattis45d81842021-01-10 14:24:24 -080011002 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11003 new Pair<>(preference, listener)));
11004 }
11005
James Mattisfa270db2021-05-31 17:11:10 -070011006 /**
11007 * Check the validity of an OEM network preference to be used for testing purposes.
11008 * @param preference the preference to validate
11009 * @return true if this is a valid OEM network preference test request.
11010 */
11011 private boolean isValidTestOemNetworkPreference(
11012 @NonNull final OemNetworkPreferences preference) {
11013 // Allow for clearing of an existing OemNetworkPreference used for testing.
11014 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11015 // changes after this check is complete. This is an unlikely scenario as calling of this API
11016 // is controlled by the OEM therefore the added complexity is not worth adding given those
11017 // circumstances. That said, it is an edge case to be aware of hence this comment.
11018 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11019 && isTestOemNetworkPreference(mOemNetworkPreferences);
11020 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11021 }
11022
11023 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11024 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11025 return prefMap.size() == 1
11026 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11027 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11028 }
11029
James Mattis45d81842021-01-10 14:24:24 -080011030 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11031 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11032 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011033 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11034 throw new IllegalArgumentException(
11035 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11036 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011037 }
11038 }
11039 }
11040
11041 private void handleSetOemNetworkPreference(
11042 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011043 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011044 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11045 if (DBG) {
11046 log("set OEM network preferences :" + preference.toString());
11047 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011048
James Mattiscb1e0362021-04-06 17:07:42 -070011049 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011050 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11051 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11052 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011053 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011054
11055 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011056 try {
11057 listener.onComplete();
11058 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011059 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011060 }
James Mattis45d81842021-01-10 14:24:24 -080011061 }
11062 }
11063
paulhu74128522021-09-28 02:29:03 +000011064 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011065 // Skip the requests which are set by other network preference. Because the uid range rules
11066 // should stay in netd.
11067 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011068 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011069 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011070 }
11071
James Mattis3ce3d3c2021-02-09 18:18:28 -080011072 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11073 ensureRunningOnConnectivityServiceThread();
11074 mDefaultNetworkRequests.addAll(nris);
11075 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11076 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011077 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011078 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11079 nrisToRegister.addAll(
11080 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11081 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011082 }
11083
11084 /**
11085 * All current requests that are tracking the default network need to be assessed as to whether
11086 * or not the current set of per-application default requests will be changing their default
11087 * network. If so, those requests will need to be updated so that they will send callbacks for
11088 * default network changes at the appropriate time. Additionally, those requests tracking the
11089 * default that were previously updated by this flow will need to be reassessed.
11090 * @return the nris which will need to be updated.
11091 */
11092 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11093 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11094 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11095 // same nri in the map's values for each of its NetworkRequest objects.
11096 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011097 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011098 // Include this nri if it is currently being tracked.
11099 if (isPerAppTrackedNri(nri)) {
11100 defaultCallbackRequests.add(nri);
11101 continue;
11102 }
11103 // We only track callbacks for requests tracking the default.
11104 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11105 continue;
11106 }
11107 // Include this nri if it will be tracked by the new per-app default requests.
11108 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011109 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011110 if (isNriGoingToBeTracked) {
11111 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011112 }
11113 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011114 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011115 }
11116
James Mattis3ce3d3c2021-02-09 18:18:28 -080011117 /**
11118 * Create nris for those network requests that are currently tracking the default network that
11119 * are being controlled by a per-application default.
11120 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11121 * foundation when creating the nri. Important items include the calling uid's original
11122 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11123 * requests are assumed to have already been validated as needing to be updated.
11124 * @return the Set of nris to use when registering network requests.
11125 */
11126 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11127 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11128 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11129 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11130 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011131 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011132
Chalard Jean9473c982021-07-29 20:03:04 +090011133 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011134 if (trackingNri == mDefaultRequest) {
11135 callbackRequestsToRegister.add(new NetworkRequestInfo(
11136 callbackRequest,
11137 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11138 continue;
11139 }
11140
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011141 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011142 callbackRequestsToRegister.add(new NetworkRequestInfo(
11143 callbackRequest,
11144 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011145 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011146 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011147 }
11148 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011149 }
11150
Chalard Jean17215832021-03-01 14:06:28 +090011151 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11152 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011153 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011154 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011155 }
11156 }
11157
James Mattis45d81842021-01-10 14:24:24 -080011158 /**
11159 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11160 */
11161 @VisibleForTesting
11162 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011163 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011164 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011165 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011166 final SparseArray<Set<Integer>> uids =
11167 createUidsFromOemNetworkPreferences(preference);
11168 for (int i = 0; i < uids.size(); i++) {
11169 final int key = uids.keyAt(i);
11170 final Set<Integer> value = uids.valueAt(i);
11171 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11172 // No need to add an nri without any requests.
11173 if (0 == nri.mRequests.size()) {
11174 continue;
11175 }
11176 nris.add(nri);
11177 }
11178
11179 return nris;
11180 }
11181
11182 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11183 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011184 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011185 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011186 final List<UserHandle> users =
11187 mContext.getSystemService(UserManager.class).getUserHandles(true);
11188 if (null == users || users.size() == 0) {
11189 if (VDBG || DDBG) {
11190 log("No users currently available for setting the OEM network preference.");
11191 }
James Mattisb6b6a432021-06-01 22:30:36 -070011192 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011193 }
James Mattis45d81842021-01-10 14:24:24 -080011194 for (final Map.Entry<String, Integer> entry :
11195 preference.getNetworkPreferences().entrySet()) {
11196 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011197 // Add the rules for all users as this policy is device wide.
11198 for (final UserHandle user : users) {
11199 try {
11200 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11201 if (!prefToUids.contains(pref)) {
11202 prefToUids.put(pref, new ArraySet<>());
11203 }
11204 prefToUids.get(pref).add(uid);
11205 } catch (PackageManager.NameNotFoundException e) {
11206 // Although this may seem like an error scenario, it is ok that uninstalled
11207 // packages are sent on a network preference as the system will watch for
11208 // package installations associated with this network preference and update
11209 // accordingly. This is done to minimize race conditions on app install.
11210 continue;
James Mattis45d81842021-01-10 14:24:24 -080011211 }
James Mattis45d81842021-01-10 14:24:24 -080011212 }
11213 }
James Mattisb6b6a432021-06-01 22:30:36 -070011214 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011215 }
11216
11217 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11218 @OemNetworkPreferences.OemNetworkPreference final int preference,
11219 @NonNull final Set<Integer> uids) {
11220 final List<NetworkRequest> requests = new ArrayList<>();
11221 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11222 switch (preference) {
11223 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11224 requests.add(createUnmeteredNetworkRequest());
11225 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011226 requests.add(createDefaultInternetRequestForTransport(
11227 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011228 break;
11229 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11230 requests.add(createUnmeteredNetworkRequest());
11231 requests.add(createOemPaidNetworkRequest());
11232 break;
11233 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11234 requests.add(createOemPaidNetworkRequest());
11235 break;
11236 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11237 requests.add(createOemPrivateNetworkRequest());
11238 break;
James Mattisfa270db2021-05-31 17:11:10 -070011239 case OEM_NETWORK_PREFERENCE_TEST:
11240 requests.add(createUnmeteredNetworkRequest());
11241 requests.add(createTestNetworkRequest());
11242 requests.add(createDefaultRequest());
11243 break;
11244 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11245 requests.add(createTestNetworkRequest());
11246 break;
James Mattis45d81842021-01-10 14:24:24 -080011247 default:
11248 // This should never happen.
11249 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11250 + " called with invalid preference of " + preference);
11251 }
11252
James Mattisfa270db2021-05-31 17:11:10 -070011253 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011254 for (final int uid : uids) {
11255 ranges.add(new UidRange(uid, uid));
11256 }
11257 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011258 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011259 }
11260
11261 private NetworkRequest createUnmeteredNetworkRequest() {
11262 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11263 .addCapability(NET_CAPABILITY_NOT_METERED)
11264 .addCapability(NET_CAPABILITY_VALIDATED);
11265 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11266 }
11267
11268 private NetworkRequest createOemPaidNetworkRequest() {
11269 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11270 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11271 .addCapability(NET_CAPABILITY_OEM_PAID)
11272 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11273 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11274 }
11275
11276 private NetworkRequest createOemPrivateNetworkRequest() {
11277 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11278 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11279 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11280 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11281 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11282 }
11283
11284 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011285 final NetworkCapabilities netcap = new NetworkCapabilities();
11286 netcap.addCapability(NET_CAPABILITY_INTERNET);
11287 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11288 return netcap;
11289 }
11290
11291 private NetworkRequest createTestNetworkRequest() {
11292 final NetworkCapabilities netcap = new NetworkCapabilities();
11293 netcap.clearAll();
11294 netcap.addTransportType(TRANSPORT_TEST);
11295 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011296 }
James Mattis47db0582021-01-01 14:13:35 -080011297 }
markchien738ad912021-12-09 18:15:45 +080011298
11299 @Override
11300 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11301 enforceNetworkStackOrSettingsPermission();
11302
11303 try {
11304 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011305 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011306 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011307 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011308 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011309 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011310 throw new IllegalStateException(e);
11311 }
11312 }
11313
11314 @Override
11315 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11316 enforceNetworkStackOrSettingsPermission();
11317
11318 try {
11319 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011320 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011321 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011322 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011323 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011324 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011325 throw new IllegalStateException(e);
11326 }
11327 }
markchiene1561fa2021-12-09 22:00:56 +080011328
11329 @Override
markchien3c04e662022-03-22 16:29:56 +080011330 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011331 enforceNetworkStackOrSettingsPermission();
11332
markchien3c04e662022-03-22 16:29:56 +080011333 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11334 int firewallRule = getFirewallRuleType(chain, rule);
11335
11336 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11337 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11338 }
11339
markchiene1561fa2021-12-09 22:00:56 +080011340 try {
markchien3c04e662022-03-22 16:29:56 +080011341 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011342 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011343 throw new IllegalStateException(e);
11344 }
11345 }
markchien98a6f952022-01-13 23:43:53 +080011346
markchien3c04e662022-03-22 16:29:56 +080011347 private int getFirewallRuleType(int chain, int rule) {
11348 final int defaultRule;
11349 switch (chain) {
11350 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011351 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11352 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011353 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011354 defaultRule = FIREWALL_RULE_ALLOW;
11355 break;
11356 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11357 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11358 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11359 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11360 defaultRule = FIREWALL_RULE_DENY;
11361 break;
11362 default:
11363 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11364 }
11365 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11366
11367 return rule;
11368 }
11369
markchien98a6f952022-01-13 23:43:53 +080011370 @Override
11371 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11372 enforceNetworkStackOrSettingsPermission();
11373
11374 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011375 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011376 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011377 throw new IllegalStateException(e);
11378 }
11379 }
11380
markchien00a0bed2022-01-13 23:46:13 +080011381 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011382 public boolean getFirewallChainEnabled(final int chain) {
11383 enforceNetworkStackOrSettingsPermission();
11384
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011385 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011386 }
11387
11388 @Override
markchien00a0bed2022-01-13 23:46:13 +080011389 public void replaceFirewallChain(final int chain, final int[] uids) {
11390 enforceNetworkStackOrSettingsPermission();
11391
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011392 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011393 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011394}