blob: 3d646fd9912d93b3637834c1dc107039d5a3c764 [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;
Mark Fasheh7c999d82023-05-04 20:23:11 +000020import static android.app.ActivityManager.UidFrozenStateChangedCallback.UID_FROZEN_STATE_FROZEN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090021import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
Chalard Jeane0aaca52023-10-17 13:23:07 +090022import static android.content.pm.PackageManager.FEATURE_LEANBACK;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090023import static android.content.pm.PackageManager.FEATURE_WATCH;
24import static android.content.pm.PackageManager.FEATURE_WIFI;
25import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090026import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090027import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
28import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
29import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
33import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
34import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Junyu Lai38c75032023-12-04 07:52:19 +000035import static android.net.ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090036import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
37import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000038import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Aaron Huang9fe47be2021-06-08 13:11:45 +080039import static android.net.ConnectivityManager.CALLBACK_IP_CHANGED;
Jeff Sharkey971cd162011-08-29 16:02:57 -070040import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Suprabh Shukla22ea1662024-02-08 16:06:01 -080041import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
markchien3c04e662022-03-22 16:29:56 +080042import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
43import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
44import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090045import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090046import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090047import static android.net.ConnectivityManager.TYPE_MOBILE;
48import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
49import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
50import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
51import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
52import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
53import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
54import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
55import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
56import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070057import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090058import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070059import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090060import static android.net.ConnectivityManager.TYPE_WIFI;
61import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070062import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070063import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080064import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080065import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070067import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080068import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Yang Sunca537d52024-01-19 12:53:50 +080069import static android.net.MulticastRoutingConfig.FORWARD_NONE;
Paul Jensen53f08952015-06-16 14:27:36 -040070import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090076import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
77import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090079import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080080import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090081import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080082import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
83import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080084import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090085import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090086import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080087import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
88import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080089import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
90import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
91import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090092import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090093import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060094import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070095import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080096import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090097import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070098import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
99import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700100import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +0800101import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100102import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700103import static android.system.OsConstants.IPPROTO_TCP;
104import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900105
Junyu Lai155760b2023-10-05 14:51:00 +0800106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
108import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
109import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
110import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900111import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
paulhu3ffffe72021-09-16 10:15:22 +0800112import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
113import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
114import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Junyu Lai71b51532024-02-01 10:39:01 +0800115import static com.android.net.module.util.PermissionUtils.hasAnyPermissionOf;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900116import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Ying Xu7cabd322024-01-15 18:40:15 -0800117import static com.android.server.connectivity.ConnectivityFlags.REQUEST_RESTRICTED_WIFI;
Chalard Jeaneb663892023-10-07 15:17:07 +0900118
Chalard Jean5b639762020-03-09 21:25:37 +0900119import android.Manifest;
Junyu Lai71b51532024-02-01 10:39:01 +0800120import android.annotation.CheckResult;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000121import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800122import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600123import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800124import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000125import android.app.ActivityManager;
126import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800127import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800128import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700129import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700130import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900131import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800132import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700133import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800134import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135import android.content.ContentResolver;
136import android.content.Context;
137import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700138import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800139import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900140import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700141import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800142import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900143import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900144import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700145import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800146import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800147import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800148import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900149import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800150import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900151import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800152import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900153import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800154import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700155import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900156import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800157import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800159import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800160import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800161import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900162import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900163import android.net.INetworkMonitor;
164import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900165import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900166import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700167import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800168import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900169import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900170import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900171import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800172import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900173import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900174import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100175import android.net.MatchAllNetworkSpecifier;
Yang Sun29037f62023-12-04 10:31:58 +0800176import android.net.MulticastRoutingConfig;
Ken Chen6df7a902021-04-09 15:08:42 +0800177import android.net.NativeNetworkConfig;
178import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800179import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700180import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700181import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900182import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700183import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800184import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700185import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900186import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900187import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000188import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900189import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700190import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900191import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700192import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900193import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700194import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800195import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900196import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700197import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000198import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800199import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900200import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800201import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400202import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700203import android.net.QosCallbackException;
204import android.net.QosFilter;
205import android.net.QosSocketFilter;
206import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700207import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800208import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800209import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900210import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400211import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800212import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800213import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400214import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800215import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900216import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900217import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900218import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900219import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800220import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900221import android.net.networkstack.ModuleNetworkStackClient;
222import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900223import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800224import android.net.resolv.aidl.DnsHealthEventParcel;
225import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
226import android.net.resolv.aidl.Nat64PrefixEventParcel;
227import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900228import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900229import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800230import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800232import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700233import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000234import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800235import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700236import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700237import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800238import android.os.Looper;
239import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700240import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700241import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900242import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800243import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700244import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700245import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800246import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700247import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900248import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900249import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700250import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700251import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400252import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800253import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900254import android.stats.connectivity.MeteredState;
255import android.stats.connectivity.RequestType;
256import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900257import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700258import android.system.ErrnoException;
Ying Xu0d06b942024-02-09 21:04:08 -0800259import android.telephony.SubscriptionManager;
Wink Saville32506bc2013-06-29 21:10:57 -0700260import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700261import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800262import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900263import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000264import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600265import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900266import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900267import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700268import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700269import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900270import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800271
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800272import androidx.annotation.RequiresApi;
273
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900274import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400275import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400276import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700277import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900278import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900279import com.android.metrics.ConnectionDurationForTransports;
280import com.android.metrics.ConnectionDurationPerTransports;
281import com.android.metrics.ConnectivitySampleMetricsHelper;
282import com.android.metrics.ConnectivityStateSample;
283import com.android.metrics.NetworkCountForTransports;
284import com.android.metrics.NetworkCountPerTransports;
285import com.android.metrics.NetworkDescription;
286import com.android.metrics.NetworkList;
287import com.android.metrics.NetworkRequestCount;
288import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800289import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900290import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800291import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000292import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900293import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800294import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900295import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900296import com.android.net.module.util.DeviceConfigUtils;
Junyu Lai2ff42d22023-12-07 16:57:13 +0800297import com.android.net.module.util.HandlerUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100298import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900299import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
300import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900301import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800302import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800303import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100304import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000305import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800306import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
307import com.android.networkstack.apishim.ConstantsShim;
308import com.android.networkstack.apishim.common.BroadcastOptionsShim;
309import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900310import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900311import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000312import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900313import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800314import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800315import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900316import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900317import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900318import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500319import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700320import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900321import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900322import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900323import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000324import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100325import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700326import com.android.server.connectivity.MockableSystemProperties;
Yang Sun29037f62023-12-04 10:31:58 +0800327import com.android.server.connectivity.MulticastRoutingCoordinatorService;
Chalard Jean43aae652022-09-14 21:33:06 +0900328import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700329import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600330import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900331import com.android.server.connectivity.NetworkNotificationManager;
332import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900333import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900334import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900335import com.android.server.connectivity.NetworkRanker;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000336import com.android.server.connectivity.NetworkRequestStateStatsMetrics;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700337import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900338import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900339import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700340import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900341import com.android.server.connectivity.RoutingCoordinatorService;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000342import com.android.server.connectivity.SatelliteAccessController;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800343import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000344import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800345import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600346
Josh Gao461a1222020-06-16 15:58:11 -0700347import libcore.io.IoUtils;
348
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900349import org.xmlpull.v1.XmlPullParserException;
350
The Android Open Source Project28527d22009-03-03 19:31:44 -0800351import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100352import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900353import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800354import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900355import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700356import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700357import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900358import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900359import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700360import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700361import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700362import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700363import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800364import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900365import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800366import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700367import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700368import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700369import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700370import java.util.Map;
Yang Sun29037f62023-12-04 10:31:58 +0800371import java.util.Map.Entry;
Chalard Jean524f0b12021-10-25 21:11:56 +0900372import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700373import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900374import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600375import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900376import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600377import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900378import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900379import java.util.concurrent.atomic.AtomicInteger;
Ying Xu0d06b942024-02-09 21:04:08 -0800380import java.util.function.BiConsumer;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000381import java.util.function.Consumer;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800382
383/**
384 * @hide
385 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800386public class ConnectivityService extends IConnectivityManager.Stub
387 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900388 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800389
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900390 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900391 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900392 private static final String NETWORK_ARG = "networks";
393 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800394 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900395
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900396 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900397 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
398 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800399
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900400 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700401
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100402 /**
403 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
404 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800405 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100406 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
407 * (preferably via runtime resource overlays).
408 */
409 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
410 "http://connectivitycheck.gstatic.com/generate_204";
411
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700412 // TODO: create better separation between radio types and network types
413
Robert Greenwalt2034b912009-08-12 16:08:25 -0700414 // how long to wait before switching back to a radio's default network
415 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
416 // system property that can override the above value
417 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
418 "android.telephony.apn-restore";
419
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900420 // How long to wait before putting up a "This network doesn't have an Internet connection,
421 // connect anyway?" dialog after the user selects a network that doesn't validate.
422 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
423
Chalard Jean5fb43c72022-09-08 19:03:14 +0900424 // How long to wait before considering that a network is bad in the absence of any form
425 // of connectivity (valid, partial, captive portal). If none has been detected after this
426 // delay, the stack considers this network bad, which may affect how it's handled in ranking
427 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900428 // Timeout in case the "actively prefer bad wifi" feature is on
429 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
430 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900431 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900432
junyulai0ac374f2020-12-14 18:41:52 +0800433 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900434 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
435 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800436 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700437
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800438 // Delimiter used when creating the broadcast delivery group for sending
439 // CONNECTIVITY_ACTION broadcast.
440 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
441
he_won.hwang881307a2022-03-15 21:23:52 +0900442 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900443 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900444
Daniel Brightf9e945b2020-06-15 16:10:01 -0700445 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900446 @VisibleForTesting
447 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700448
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900449 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700450 @VisibleForTesting
451 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900452
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900453 @VisibleForTesting
454 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800455 @VisibleForTesting
456 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900457 // True if the cell radio of the device is capable of time-sharing.
458 @VisibleForTesting
459 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900460
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800461 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800462 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800463 private final int mReleasePendingIntentDelayMs;
464
Chalard Jean46bfbf02022-02-02 00:56:25 +0900465 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900466
Motomu Utsumif360aa62023-01-30 17:52:20 +0900467 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700468
Chalard Jean9473c982021-07-29 20:03:04 +0900469 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800470 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700471 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800472 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700473
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900474 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700475
Ying Xu7cabd322024-01-15 18:40:15 -0800476 private final boolean mRequestRestrictedWifiEnabled;
477
junyulaif2c67e42018-08-07 19:50:45 +0800478 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000479 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
480 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800481 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900482 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800483
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900484 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900485 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000486 private final int mWakeUpMark;
487 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000488 // The Context is created for UserHandle.ALL.
489 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900490 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900491 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700492 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700493 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800494
Chenbo Feng15416292018-11-08 17:36:21 -0800495 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800496 protected IDnsResolver mDnsResolver;
497 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800498 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700499 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900500 private final NetworkStatsManager mStatsManager;
501 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800502 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700503
Benedict Wong493e04b2018-11-09 14:45:34 -0800504 /**
505 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
506 * instances.
507 */
508 @GuardedBy("mTNSLock")
509 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800510 private final CompanionDeviceManagerProxyService mCdmps;
Yang Sun29037f62023-12-04 10:31:58 +0800511 private final MulticastRoutingCoordinatorService mMulticastRoutingCoordinatorService;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900512 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800513
514 private final Object mTNSLock = new Object();
515
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700516 private String mCurrentTcpBufferSizes;
517
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900518 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000519 new Class[] {
520 ConnectivityService.class,
521 NetworkAgent.class,
522 NetworkAgentInfo.class,
523 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900524
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500525 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400526 // Tear down networks that have no chance (e.g. even if validated) of becoming
527 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500528 // all networks have been rematched against all NetworkRequests.
529 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400530 // Don't reap networks. This should be passed when some networks have not yet been
531 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500532 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900533 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500534
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900535 private enum UnneededFor {
536 LINGER, // Determine whether this network is unneeded and should be lingered.
537 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
538 }
539
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700540 /**
paulhuaa0743d2021-05-26 21:56:03 +0800541 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800542 * should have priority. The order is passed to netd which will use it together
543 * with UID ranges to generate the corresponding IP rule. This serves to
544 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800545 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800546 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000547 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800548 *
paulhu48291862021-07-14 14:53:57 +0800549 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
550 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800551 */
paulhu48291862021-07-14 14:53:57 +0800552 // Used when sending to netd to code for "no order".
553 static final int PREFERENCE_ORDER_NONE = 0;
554 // Order for requests that don't code for a per-app preference. As it is
555 // out of the valid range, the corresponding order should be
556 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800557 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800558 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800559 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800560 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
561 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800562 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800563 static final int PREFERENCE_ORDER_OEM = 10;
564 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800565 // See {@link #setProfileNetworkPreference}.
566 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800567 static final int PREFERENCE_ORDER_PROFILE = 20;
568 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800569 // better scores are connected.
570 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800571 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800572 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000573 // Order of setting satellite network preference fallback when default message application
574 // with role_sms role and android.permission.SATELLITE_COMMUNICATION permission detected
575 @VisibleForTesting
576 static final int PREFERENCE_ORDER_SATELLITE_FALLBACK = 40;
Chalard Jeane6c95272022-01-25 21:04:21 +0900577 // Preference order that signifies the network shouldn't be set as a default network for
578 // the UIDs, only give them access to it. TODO : replace this with a boolean
579 // in NativeUidRangeConfig
580 @VisibleForTesting
581 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
582 // Bound for the lowest valid preference order.
583 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800584
585 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700586 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700587 * from one net to another. Clear happens when we get a new
588 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
589 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700590 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700591 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700592
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700593 /**
594 * used internally to reload global proxy settings
595 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700596 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700597
Robert Greenwalt34848c02011-03-25 13:09:25 -0700598 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400599 * PAC manager has received new port.
600 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800601 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400602
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700603 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900604 * used internally when registering NetworkProviders
605 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700606 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900607 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700608
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700609 /**
610 * used internally when registering NetworkAgents
611 * obj = Messenger
612 */
613 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
614
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700615 /**
616 * used to add a network request
617 * includes a NetworkRequestInfo
618 */
619 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
620
621 /**
622 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900623 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700624 * cancel it.
625 * includes a NetworkRequestInfo
626 */
627 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
628
629 /**
630 * used to add a network listener - no request
631 * includes a NetworkRequestInfo
632 */
633 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
634
635 /**
636 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400637 * arg1 = UID of caller
638 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700639 */
640 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
641
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700642 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900643 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700644 * obj = Messenger
645 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900646 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700647
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700648 /**
649 * used internally to expire a wakelock when transitioning
650 * from one net to another. Expire happens when we fail to find
651 * a new network (typically after 1 minute) -
652 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
653 * a replacement network.
654 */
655 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
656
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700657 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800658 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400659 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800660 */
661 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
662
663 /**
664 * used to remove a pending intent and its associated network request.
665 * arg1 = UID of caller
666 * obj = PendingIntent
667 */
668 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
669
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900670 /**
671 * used to specify whether a network should be used even if unvalidated.
672 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
673 * arg2 = whether to remember this choice in the future (1 or 0)
674 * obj = network
675 */
676 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
677
678 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700679 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900680 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700681 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900682
Paul Jensenc8873fc2015-06-17 14:15:39 -0400683 /**
684 * used to add a network listener with a pending intent
685 * obj = NetworkRequestInfo
686 */
687 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
688
Hugo Benichid6b510a2017-04-06 17:22:18 +0900689 /**
690 * used to specify whether a network should not be penalized when it becomes unvalidated.
691 */
692 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
693
694 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700695 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900696 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700697 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900698
Erik Kline31b4a9e2018-01-11 21:07:29 +0900699 // Handle changes in Private DNS settings.
700 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
701
dalyk1720e542018-03-05 12:42:22 -0500702 // Handle private DNS validation status updates.
703 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
704
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900705 /**
706 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
707 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800708 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
709 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
710 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900711 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900712 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900713
714 /**
715 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
716 * config was resolved.
717 * obj = PrivateDnsConfig
718 * arg2 = netid
719 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900720 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900721
722 /**
723 * Request ConnectivityService display provisioning notification.
724 * arg1 = Whether to make the notification visible.
725 * arg2 = NetID.
726 * obj = Intent to be launched when notification selected by user, null if !arg1.
727 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900728 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900729
730 /**
lucaslin2240ef62019-03-12 13:08:03 +0800731 * Used to specify whether a network should be used even if connectivity is partial.
732 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
733 * false)
734 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
735 * obj = network
736 */
lucaslin444d43a2020-02-20 16:56:59 +0800737 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800738
739 /**
lucasline117e2e2019-10-22 18:27:33 +0800740 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
741 * Both of the arguments are bitmasks, and the value of bits come from
742 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900743 * arg1 = unused
744 * arg2 = netId
745 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800746 */
lucaslin444d43a2020-02-20 16:56:59 +0800747 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800748
749 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900750 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
751 * arg1 = unused
752 * arg2 = netId
753 * obj = captive portal data
754 */
lucaslin444d43a2020-02-20 16:56:59 +0800755 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900756
757 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900758 * Used by setRequireVpnForUids.
759 * arg1 = whether the specified UID ranges are required to use a VPN.
760 * obj = Array of UidRange objects.
761 */
762 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
763
764 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900765 * Used internally when setting the default networks for OemNetworkPreferences.
766 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800767 */
768 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
769
770 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800771 * Used to indicate the system default network becomes active.
772 */
773 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
774
775 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900776 * Used internally when setting a network preference for a user profile.
777 * obj = Pair<ProfileNetworkPreference, Listener>
778 */
779 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
780
781 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000782 * Event to specify that reasons for why an uid is blocked changed.
783 * arg1 = uid
784 * arg2 = blockedReasons
785 */
786 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
787
788 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900789 * Event to register a new network offer
790 * obj = NetworkOffer
791 */
792 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
793
794 /**
795 * Event to unregister an existing network offer
796 * obj = INetworkOfferCallback
797 */
798 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
799
800 /**
paulhu51f77dc2021-06-07 02:34:20 +0000801 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
802 */
803 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
804
805 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800806 * Event to set temporary allow bad wifi within a limited time to override
807 * {@code config_networkAvoidBadWifi}.
808 */
809 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
810
811 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100812 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
813 */
814 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
815
816 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900817 * The initial evaluation period is over for this network.
818 *
819 * If no form of connectivity has been found on this network (valid, partial, captive portal)
820 * then the stack will now consider it to have been determined bad.
821 */
822 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
823
824 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000825 * Used internally when the user does not want the network from captive portal app.
826 * obj = Network
827 */
828 private static final int EVENT_USER_DOES_NOT_WANT = 58;
829
830 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000831 * Event to set VPN as preferred network for specific apps.
832 * obj = VpnNetworkPreferenceInfo
833 */
834 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
835
836 /**
chiachangwange0192a72023-02-06 13:25:01 +0000837 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
838 */
839 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
840
841 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000842 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
843 */
844 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
845
846 /**
Ying Xu7cabd322024-01-15 18:40:15 -0800847 * Event to inform the ConnectivityService handler when a uid has lost carrier privileges.
848 */
849 private static final int EVENT_UID_CARRIER_PRIVILEGES_LOST = 62;
850
851 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900852 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
853 * should be shown.
854 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900855 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900856
857 /**
858 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
859 * should be hidden.
860 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900861 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900862
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800863 /**
864 * The maximum alive time to allow bad wifi configuration for testing.
865 */
866 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
867
Patrick Rohr2857ac42022-01-21 14:58:16 +0100868 /**
chiachangwange0192a72023-02-06 13:25:01 +0000869 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
870 * testing.
871 */
872 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
873
874 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100875 * The priority of the tc police rate limiter -- smaller value is higher priority.
876 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
877 */
878 private static final short TC_PRIO_POLICE = 1;
879
880 /**
881 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
882 */
883 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700884 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100885
Hugo Benichi47011212017-03-30 10:46:05 +0900886 private static String eventName(int what) {
887 return sMagicDecoderRing.get(what, Integer.toString(what));
888 }
889
paulhua10d8212020-11-10 15:32:56 +0800890 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900891 final DnsResolverServiceManager dsm = context.getSystemService(
892 DnsResolverServiceManager.class);
893 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800894 }
895
Cody Kesting73708bf2019-12-18 10:57:50 -0800896 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900897 @VisibleForTesting
898 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700899 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700900 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700901 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700902 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800903 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
904 @VisibleForTesting
905 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
906
Erik Kline32120082017-12-13 19:40:49 +0900907 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900908 @VisibleForTesting
909 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700910
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400911 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800912 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400913
Chalard Jean46bfbf02022-02-02 00:56:25 +0900914 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800915 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700916
Chalard Jean5d70ba42018-06-07 16:44:04 +0900917 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
918 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800919 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400920
Erik Kline05f2b402015-04-30 12:58:40 +0900921 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700922
Chalard Jean46bfbf02022-02-02 00:56:25 +0900923 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400924
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700925 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900926 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700927
Valentin Iftime9fa35092019-09-24 13:32:13 +0200928 private Set<String> mWolSupportedInterfaces;
929
Roshan Pius08c94fb2020-01-16 12:17:17 -0800930 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800931 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800932 private final AppOpsManager mAppOpsManager;
933
934 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400935
chiachangwang3d60bac2023-01-17 14:38:08 +0000936 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900937 private final QosCallbackTracker mQosCallbackTracker;
938 private final NetworkNotificationManager mNotifier;
939 private final LingerMonitor mLingerMonitor;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000940 private final SatelliteAccessController mSatelliteAccessController;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900941
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700942 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800943 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700944
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900945 // Sequence number for NetworkProvider IDs.
946 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
947 NetworkProvider.FIRST_PROVIDER_ID);
948
Erik Klineedf878b2015-07-09 18:24:03 +0900949 // NetworkRequest activity String log entries.
950 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
951 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
952
Hugo Benichid159fdd2016-07-11 11:05:12 +0900953 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900954 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900955 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
956
Hugo Benichi47011212017-03-30 10:46:05 +0900957 private static final int MAX_WAKELOCK_LOGS = 20;
958 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900959 private int mTotalWakelockAcquisitions = 0;
960 private int mTotalWakelockReleases = 0;
961 private long mTotalWakelockDurationMs = 0;
962 private long mMaxWakelockDurationMs = 0;
963 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900964
Hugo Benichi208c0102016-07-28 17:53:06 +0900965 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900966
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000967 @Nullable private final NetworkRequestStateStatsMetrics mNetworkRequestStateStatsMetrics;
968
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700969 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900970 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700971
Erik Kline95ecfee2016-10-02 18:02:14 +0900972 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900973 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900974
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900975 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800976 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
977 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800978
Patrick Rohr2857ac42022-01-21 14:58:16 +0100979 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
980 // configured via {@link
981 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
982 // Only the handler thread is allowed to access this field.
983 private long mIngressRateLimit = -1;
984
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900985 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
986 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900987 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900988 @GuardedBy("mSelfCertifiedCapabilityCache")
989 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
990 mSelfCertifiedCapabilityCache = new HashMap<>();
991
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900992 // Flag to enable the feature of closing frozen app sockets.
993 private final boolean mDestroyFrozenSockets;
994
995 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
996 private final boolean mDelayDestroyFrozenSockets;
997
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900998 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
999 private final boolean mAllowSysUiConnectivityReports;
1000
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001001 // Uids that ConnectivityService is pending to close sockets of.
1002 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
1003
Robert Greenwalt802c1102014-06-02 15:32:02 -07001004 /**
1005 * Implements support for the legacy "one network per network type" model.
1006 *
1007 * We used to have a static array of NetworkStateTrackers, one for each
1008 * network type, but that doesn't work any more now that we can have,
1009 * for example, more that one wifi network. This class stores all the
1010 * NetworkAgentInfo objects that support a given type, but the legacy
1011 * API will only see the first one.
1012 *
1013 * It serves two main purposes:
1014 *
1015 * 1. Provide information about "the network for a given type" (since this
1016 * API only supports one).
1017 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
1018 * the first network for a given type changes, or if the default network
1019 * changes.
1020 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001021 @VisibleForTesting
1022 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001023
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09001024 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001025 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001026
Robert Greenwalt802c1102014-06-02 15:32:02 -07001027 /**
1028 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1029 * Each list holds references to all NetworkAgentInfos that are used to
1030 * satisfy requests for that network type.
1031 *
1032 * This array is built out at startup such that an unsupported network
1033 * doesn't get an ArrayList instance, making this a tristate:
1034 * unsupported, supported but not active and active.
1035 *
1036 * The actual lists are populated when we scan the network types that
1037 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001038 *
1039 * Threading model:
1040 * - addSupportedType() is only called in the constructor
1041 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1042 * They are therefore not thread-safe with respect to each other.
1043 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1044 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001045 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001046 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001047 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001048 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001049 @NonNull
1050 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001051
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001052 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1053 // an entry have no timer (equivalent to -1). Lazily loaded.
1054 @NonNull
1055 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1056
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001057 LegacyTypeTracker(@NonNull ConnectivityService service) {
1058 mService = service;
1059 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001060 }
1061
Chiachang Wang3bc52762021-11-25 14:17:57 +08001062 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1063 // addressed.
1064 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001065 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1066 final PackageManager pm = ctx.getPackageManager();
1067 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1068 addSupportedType(TYPE_WIFI);
1069 }
1070 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1071 addSupportedType(TYPE_WIFI_P2P);
1072 }
1073 if (tm.isDataCapable()) {
1074 // Telephony does not have granular support for these types: they are either all
1075 // supported, or none is supported
1076 addSupportedType(TYPE_MOBILE);
1077 addSupportedType(TYPE_MOBILE_MMS);
1078 addSupportedType(TYPE_MOBILE_SUPL);
1079 addSupportedType(TYPE_MOBILE_DUN);
1080 addSupportedType(TYPE_MOBILE_HIPRI);
1081 addSupportedType(TYPE_MOBILE_FOTA);
1082 addSupportedType(TYPE_MOBILE_IMS);
1083 addSupportedType(TYPE_MOBILE_CBS);
1084 addSupportedType(TYPE_MOBILE_IA);
1085 addSupportedType(TYPE_MOBILE_EMERGENCY);
1086 }
1087 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1088 addSupportedType(TYPE_BLUETOOTH);
1089 }
1090 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1091 // TYPE_PROXY is only used on Wear
1092 addSupportedType(TYPE_PROXY);
1093 }
1094 // Ethernet is often not specified in the configs, although many devices can use it via
1095 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001096 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001097 addSupportedType(TYPE_ETHERNET);
1098 }
1099
1100 // Always add TYPE_VPN as a supported type
1101 addSupportedType(TYPE_VPN);
1102 }
1103
1104 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001105 if (mTypeLists[type] != null) {
1106 throw new IllegalStateException(
1107 "legacy list for type " + type + "already initialized");
1108 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001109 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001110 }
1111
Robert Greenwalt802c1102014-06-02 15:32:02 -07001112 public boolean isTypeSupported(int type) {
1113 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1114 }
1115
1116 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001117 synchronized (mTypeLists) {
1118 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1119 return mTypeLists[type].get(0);
1120 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001121 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001122 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001123 }
1124
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001125 public int getRestoreTimerForType(int type) {
1126 synchronized (mTypeLists) {
1127 if (mRestoreTimers == null) {
1128 mRestoreTimers = loadRestoreTimers();
1129 }
1130 return mRestoreTimers.getOrDefault(type, -1);
1131 }
1132 }
1133
1134 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1135 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001136 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001137 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1138 for (final String config : configs) {
1139 final String[] splits = TextUtils.split(config, ",");
1140 if (splits.length != 2) {
1141 logwtf("Invalid restore timer token count: " + config);
1142 continue;
1143 }
1144 try {
1145 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1146 } catch (NumberFormatException e) {
1147 logwtf("Invalid restore timer number format: " + config, e);
1148 }
1149 }
1150 return ret;
1151 }
1152
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001153 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001154 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001155 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001156 log("Sending " + state
1157 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001158 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001159 }
1160 }
1161
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001162 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1163 // network type, to preserve previous behaviour.
1164 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1165 if (vpnNai != mService.getLegacyLockdownNai()) return;
1166
1167 if (vpnNai.declaredUnderlyingNetworks == null
1168 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1169 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1170 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1171 return;
1172 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001173 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001174 vpnNai.declaredUnderlyingNetworks[0]);
1175 if (underlyingNai == null) return;
1176
1177 final int type = underlyingNai.networkInfo.getType();
1178 final DetailedState state = DetailedState.CONNECTED;
1179 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1180 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1181 }
1182
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001183 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001184 public void add(int type, NetworkAgentInfo nai) {
1185 if (!isTypeSupported(type)) {
1186 return; // Invalid network type.
1187 }
1188 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1189
1190 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1191 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001192 return;
1193 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001194 synchronized (mTypeLists) {
1195 list.add(nai);
1196 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001197
Chalard Jean5b409c72021-02-04 13:12:59 +09001198 // Send a broadcast if this is the first network of its type or if it's the default.
1199 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001200
1201 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1202 // to preserve previous behaviour.
1203 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001204 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001205 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1206 mService.sendLegacyNetworkBroadcast(nai, state, type);
1207 }
1208
1209 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1210 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001211 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001212 }
1213
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001214 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001215 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001216 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1217 if (list == null || list.isEmpty()) {
1218 return;
1219 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001220 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001221
Hugo Benichi389633f2016-06-21 09:48:07 +09001222 synchronized (mTypeLists) {
1223 if (!list.remove(nai)) {
1224 return;
1225 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001226 }
1227
Lorenzo Colitti49767722015-05-01 00:30:10 +09001228 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001229 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1230 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001231 }
1232
1233 if (!list.isEmpty() && wasFirstNetwork) {
1234 if (DBG) log("Other network available for type " + type +
1235 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001236 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001237 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001238 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001239 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001240 }
1241 }
1242
1243 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001244 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1245 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001246 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001247 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001248 }
1249 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001250
Chalard Jean46bfbf02022-02-02 00:56:25 +09001251 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001252 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001253 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001254 final DetailedState state = nai.networkInfo.getDetailedState();
1255 for (int type = 0; type < mTypeLists.length; type++) {
1256 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001257 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001258 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001259 if (isFirst || contains && isDefault) {
1260 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001261 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001262 }
1263 }
1264 }
1265
Robert Greenwalt94e22142014-07-30 16:31:24 -07001266 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001267 pw.println("mLegacyTypeTracker:");
1268 pw.increaseIndent();
1269 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001270 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001271 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001272 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001273 pw.println();
1274 pw.println("Current state:");
1275 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001276 synchronized (mTypeLists) {
1277 for (int type = 0; type < mTypeLists.length; type++) {
1278 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1279 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001280 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001281 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001282 }
1283 }
1284 pw.decreaseIndent();
1285 pw.decreaseIndent();
1286 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001287 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001288 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001289 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001290
Ying Xu0d06b942024-02-09 21:04:08 -08001291 @VisibleForTesting
1292 void onCarrierPrivilegesLost(Integer uid, Integer subId) {
1293 if (mRequestRestrictedWifiEnabled) {
1294 mHandler.sendMessage(mHandler.obtainMessage(
1295 EVENT_UID_CARRIER_PRIVILEGES_LOST, uid, subId));
Ying Xu7cabd322024-01-15 18:40:15 -08001296 }
1297 }
Ying Xu0d06b942024-02-09 21:04:08 -08001298
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001299 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001300 /**
1301 * Helper class which parses out priority arguments and dumps sections according to their
1302 * priority. If priority arguments are omitted, function calls the legacy dump command.
1303 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001304 private class LocalPriorityDump {
1305 private static final String PRIORITY_ARG = "--dump-priority";
1306 private static final String PRIORITY_ARG_HIGH = "HIGH";
1307 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001308 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001309
1310 LocalPriorityDump() {}
1311
1312 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001313 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> {
Junyu Laif8dba342023-10-12 17:01:03 +08001314 doDump(fd, pw, new String[]{DIAG_ARG});
1315 doDump(fd, pw, new String[]{SHORT_ARG});
1316 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1317 pw.println("dumpHigh timeout");
1318 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001319 }
1320
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001321 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001322 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> doDump(fd, pw, args),
Junyu Laif8dba342023-10-12 17:01:03 +08001323 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1324 pw.println("dumpNormal timeout");
1325 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001326 }
1327
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001328 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1329 if (args == null) {
1330 dumpNormal(fd, pw, args);
1331 return;
1332 }
1333
1334 String priority = null;
1335 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1336 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1337 argIndex++;
1338 priority = args[argIndex];
1339 }
1340 }
1341
1342 if (PRIORITY_ARG_HIGH.equals(priority)) {
1343 dumpHigh(fd, pw);
1344 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1345 dumpNormal(fd, pw, args);
1346 } else {
1347 // ConnectivityService publishes binder service using publishBinderService() with
1348 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001349 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1350 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001351 // TODO: Integrate into signal dump.
1352 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001353 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001354 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001355 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001356
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001357 /**
1358 * Dependencies of ConnectivityService, for injection in tests.
1359 */
1360 @VisibleForTesting
1361 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001362 public int getCallingUid() {
1363 return Binder.getCallingUid();
1364 }
1365
Chalard Jeandf29a852023-05-29 17:02:43 +09001366 public boolean isAtLeastS() {
1367 return SdkLevel.isAtLeastS();
1368 }
1369
1370 public boolean isAtLeastT() {
1371 return SdkLevel.isAtLeastT();
1372 }
1373
1374 public boolean isAtLeastU() {
1375 return SdkLevel.isAtLeastU();
1376 }
1377
Chalard Jeaneb663892023-10-07 15:17:07 +09001378 public boolean isAtLeastV() {
1379 return SdkLevel.isAtLeastV();
1380 }
1381
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001382 /**
1383 * Get system properties to use in ConnectivityService.
1384 */
1385 public MockableSystemProperties getSystemProperties() {
1386 return new MockableSystemProperties();
1387 }
1388
1389 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001390 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1391 */
1392 public ConnectivityResources getResources(@NonNull Context ctx) {
1393 return new ConnectivityResources(ctx);
1394 }
1395
1396 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001397 * Create a HandlerThread to use in ConnectivityService.
1398 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001399 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1400 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001401 }
1402
1403 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001404 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001405 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001406 public NetworkStackClientBase getNetworkStack() {
1407 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001408 }
1409
1410 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001411 * @see ProxyTracker
1412 */
1413 public ProxyTracker makeProxyTracker(@NonNull Context context,
1414 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001415 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001416 }
1417
1418 /**
1419 * @see NetIdManager
1420 */
1421 public NetIdManager makeNetIdManager() {
1422 return new NetIdManager();
1423 }
1424
1425 /**
1426 * @see NetworkUtils#queryUserAccess(int, int)
1427 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001428 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1429 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001430 }
1431
1432 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001433 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1434 * requires CAP_NET_ADMIN, which the unit tests do not have.
1435 */
1436 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1437 InetSocketAddress remote) {
1438 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1439 }
1440
1441 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001442 * @see MultinetworkPolicyTracker
1443 */
1444 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1445 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1446 return new MultinetworkPolicyTracker(c, h, r);
1447 }
1448
Aaron Huang330a4c02020-10-27 03:36:19 +08001449 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001450 * @see AutomaticOnOffKeepaliveTracker
1451 */
1452 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1453 @NonNull Context c, @NonNull Handler h) {
1454 return new AutomaticOnOffKeepaliveTracker(c, h);
1455 }
1456
Yang Sun29037f62023-12-04 10:31:58 +08001457 public MulticastRoutingCoordinatorService makeMulticastRoutingCoordinatorService(
1458 @NonNull Handler h) {
1459 try {
1460 return new MulticastRoutingCoordinatorService(h);
1461 } catch (UnsupportedOperationException e) {
1462 // Multicast routing is not supported by the kernel
1463 Log.i(TAG, "Skipping unsupported MulticastRoutingCoordinatorService");
1464 return null;
1465 }
1466 }
1467
chiachangwang7c17c282023-02-02 05:58:59 +00001468 /**
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001469 * @see NetworkRequestStateStatsMetrics
1470 */
1471 public NetworkRequestStateStatsMetrics makeNetworkRequestStateStatsMetrics(
1472 Context context) {
1473 // We currently have network requests metric for Watch devices only
1474 if (context.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
1475 return new NetworkRequestStateStatsMetrics();
1476 } else {
1477 return null;
1478 }
1479 }
1480
1481 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001482 * @see BatteryStatsManager
1483 */
1484 public void reportNetworkInterfaceForTransports(Context context, String iface,
1485 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001486 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001487 context.getSystemService(BatteryStatsManager.class);
1488 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1489 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001490
1491 public boolean getCellular464XlatEnabled() {
1492 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1493 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001494
1495 /**
1496 * @see PendingIntent#intentFilterEquals
1497 */
1498 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1499 return a.intentFilterEquals(b);
1500 }
1501
1502 /**
1503 * @see LocationPermissionChecker
1504 */
1505 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1506 return new LocationPermissionChecker(context);
1507 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001508
1509 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001510 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001511 *
1512 * This method returns null in versions before T, where carrier privilege
1513 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001514 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001515 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001516 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
Ying Xu7cabd322024-01-15 18:40:15 -08001517 @NonNull final Context context,
1518 @NonNull final TelephonyManager tm,
1519 boolean requestRestrictedWifiEnabled,
Ying Xu0d06b942024-02-09 21:04:08 -08001520 @NonNull BiConsumer<Integer, Integer> listener) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001521 if (isAtLeastT()) {
Ying Xu7cabd322024-01-15 18:40:15 -08001522 return new CarrierPrivilegeAuthenticator(
1523 context, tm, requestRestrictedWifiEnabled, listener);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001524 } else {
1525 return null;
1526 }
1527 }
1528
1529 /**
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00001530 * @see SatelliteAccessController
1531 */
1532 @Nullable
1533 public SatelliteAccessController makeSatelliteAccessController(
1534 @NonNull final Context context,
1535 Consumer<Set<Integer>> updateSatelliteNetworkFallbackUidCallback,
1536 @NonNull final Handler connectivityServiceInternalHandler) {
1537 return new SatelliteAccessController(context, updateSatelliteNetworkFallbackUidCallback,
1538 connectivityServiceInternalHandler);
1539 }
1540
1541 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001542 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001543 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001544 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001545 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001546 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001547
1548 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001549 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1550 */
1551 public boolean isFeatureNotChickenedOut(Context context, String name) {
1552 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1553 }
1554
1555 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001556 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001557 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001558 * @return BpfNetMaps implementation.
1559 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001560 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1561 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001562 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001563
1564 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001565 * @see ClatCoordinator
1566 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001567 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001568 public ClatCoordinator getClatCoordinator(INetd netd) {
1569 return new ClatCoordinator(
1570 new ClatCoordinator.Dependencies() {
1571 @NonNull
1572 public INetd getNetd() {
1573 return netd;
1574 }
1575 });
1576 }
1577
1578 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001579 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1580 */
1581 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1582 final InterfaceParams params = InterfaceParams.getByName(iface);
1583 if (params == null) {
1584 // the interface might have disappeared.
1585 logw("Failed to get interface params for interface " + iface);
1586 return;
1587 }
1588 try {
1589 // converting rateInBytesPerSecond from long to int is safe here because the
1590 // setting's range is limited to INT_MAX.
1591 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001592 Log.i(TAG,
1593 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001594 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1595 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1596 } catch (IOException e) {
1597 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1598 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1599 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1600 + ") failure: ", e);
1601 }
1602 }
1603
1604 /**
1605 * Wraps {@link TcUtils#tcFilterDelDev}
1606 */
1607 public void disableIngressRateLimit(String iface) {
1608 final InterfaceParams params = InterfaceParams.getByName(iface);
1609 if (params == null) {
1610 // the interface might have disappeared.
1611 logw("Failed to get interface params for interface " + iface);
1612 return;
1613 }
1614 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001615 Log.i(TAG,
1616 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001617 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1618 } catch (IOException e) {
1619 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1620 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1621 }
1622 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001623
1624 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001625 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1626 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001627 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001628 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001629 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001630 }
1631
1632 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001633 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1634 */
1635 // TODO: when available in all active branches:
1636 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1637 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1638 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1639 return BroadcastOptionsShimImpl.newInstance(options);
1640 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001641
1642 /**
1643 * Wrapper method for
1644 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1645 *
1646 * @param changeId The ID of the compatibility change in question.
1647 * @param packageName The package name of the app in question.
1648 * @param user The user that the operation is done for.
1649 * @return {@code true} if the change is enabled for the specified package.
1650 */
1651 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1652 @NonNull final UserHandle user) {
1653 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1654 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001655
1656 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001657 * As above but with a UID.
1658 * @see CompatChanges#isChangeEnabled(long, int)
1659 */
1660 public boolean isChangeEnabled(final long changeId, final int uid) {
1661 return CompatChanges.isChangeEnabled(changeId, uid);
1662 }
1663
1664 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001665 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1666 *
1667 * @param ranges target uid ranges
1668 * @param exemptUids uids to skip close socket
1669 */
1670 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1671 @NonNull final Set<Integer> exemptUids)
1672 throws SocketException, InterruptedIOException, ErrnoException {
1673 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1674 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001675
1676 /**
1677 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1678 *
1679 * @param ownerUids target uids to close sockets
1680 */
1681 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1682 throws SocketException, InterruptedIOException, ErrnoException {
1683 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1684 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001685
1686 /**
1687 * Schedule the evaluation timeout.
1688 *
1689 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1690 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1691 * of these events happen, this time will run out, after which the network is considered
1692 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1693 * on this network and considers it won't provide connectivity. In particular, that means
1694 * it's when the system prefers it to cell if it's wifi and configuration says it should
1695 * prefer bad wifi to cell.
1696 */
1697 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1698 @NonNull final Network network, final long delayMs) {
1699 handler.sendMessageDelayed(
1700 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1701 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001702 }
1703
junyulaie7c7d2a2021-01-26 15:29:15 +08001704 public ConnectivityService(Context context) {
1705 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001706 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1707 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001708 }
1709
1710 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001711 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1712 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001713 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001714
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001715 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001716 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001717 mSystemProperties = mDeps.getSystemProperties();
1718 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001719 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001720 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001721 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1722 // Pass limit - 1 to maintain backward compatibility.
1723 // TODO: Remove the workaround.
1724 mNetworkRequestCounter =
1725 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1726 mSystemNetworkRequestCounter =
1727 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001728
Hugo Benichi208c0102016-07-28 17:53:06 +09001729 mMetricsLog = logger;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001730 mNetworkRequestStateStatsMetrics = mDeps.makeNetworkRequestStateStatsMetrics(mContext);
James Mattis45d81842021-01-10 14:24:24 -08001731 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1732 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001733 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001734 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001735 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001736 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1737 mDefaultNetworkRequests.add(mDefaultRequest);
1738 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001739
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001740 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001741 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001742
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001743 // The default WiFi request is a background request so that apps using WiFi are
1744 // migrated to a better network (typically ethernet) when one comes up, instead
1745 // of staying on WiFi forever.
1746 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1747 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1748
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001749 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1750 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1751 NetworkRequest.Type.BACKGROUND_REQUEST);
1752
Chalard Jean0702f982021-09-16 21:50:07 +09001753 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1754 // TODO: Consider making the timer customizable.
1755 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1756 mCellularRadioTimesharingCapable =
1757 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1758
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001759 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1760 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1761
1762 if (SdkLevel.isAtLeastU()) {
1763 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1764 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1765 final int defaultUMarkMask = 0x80000000; // u32
1766
1767 if ((mark == 0) || (mask == 0)) {
1768 // simply treat unset/disabled as the default U value
1769 mark = defaultUMarkMask;
1770 mask = defaultUMarkMask;
1771 }
1772 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1773 // invalid device overlay settings
1774 throw new IllegalArgumentException(
1775 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1776 }
1777 }
1778
1779 mWakeUpMark = mark;
1780 mWakeUpMask = mask;
1781
Paul Hu51f816b2022-08-11 14:43:47 +00001782 mNetd = netd;
1783 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09001784 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00001785 mPermissionMonitor =
1786 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001787 mHandlerThread.start();
1788 mHandler = new InternalHandler(mHandlerThread.getLooper());
1789 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001790 mConnectivityDiagnosticsHandler =
1791 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001792
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001793 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001794 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001795
junyulaie7c7d2a2021-01-26 15:29:15 +08001796 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001797 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001798 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001799 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001800
Wink Saville32506bc2013-06-29 21:10:57 -07001801 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001802 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001803 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Ying Xu7cabd322024-01-15 18:40:15 -08001804 mRequestRestrictedWifiEnabled = mDeps.isAtLeastU()
1805 && mDeps.isFeatureEnabled(context, REQUEST_RESTRICTED_WIFI);
1806 mCarrierPrivilegeAuthenticator = mDeps.makeCarrierPrivilegeAuthenticator(
1807 mContext, mTelephonyManager, mRequestRestrictedWifiEnabled,
Ying Xu0d06b942024-02-09 21:04:08 -08001808 this::onCarrierPrivilegesLost);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001809
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00001810 if (mDeps.isAtLeastU()
1811 && mDeps
1812 .isFeatureNotChickenedOut(mContext, ALLOW_SATALLITE_NETWORK_FALLBACK)) {
1813 mSatelliteAccessController = mDeps.makeSatelliteAccessController(
1814 mContext, this::updateSatelliteNetworkPreferenceUids, mHandler);
1815 } else {
1816 mSatelliteAccessController = null;
1817 }
1818
Sudheer Shanka9967d462021-03-18 19:09:25 +00001819 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001820 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1821 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001822 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001823
1824 final PowerManager powerManager = (PowerManager) context.getSystemService(
1825 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001826 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001827 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001828
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001829 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1830 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001831 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001832 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001833 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001834 mProtectedNetworks.add(p);
1835 } else {
1836 if (DBG) loge("Ignoring protectedNetwork " + p);
1837 }
1838 }
1839
soma, kawata29444ae2019-05-23 09:30:40 +09001840 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1841
James Mattis02220e22021-03-13 19:27:21 -08001842 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001843 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001844 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001845 final IntentFilter userIntentFilter = new IntentFilter();
1846 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1847 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1848 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1849 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001850
James Mattis02220e22021-03-13 19:27:21 -08001851 // Listen to package add/removes for netd
1852 final IntentFilter packageIntentFilter = new IntentFilter();
1853 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1854 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1855 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1856 packageIntentFilter.addDataScheme("package");
1857 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001858 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001859
Junyu Lai38c75032023-12-04 07:52:19 +00001860 // This is needed for pre-V devices to propagate the data saver status
1861 // to the BPF map. This isn't supported before Android T because BPF maps are
1862 // unsupported, and it's also unnecessary on Android V and later versions,
1863 // as the platform code handles data saver bit updates. Additionally, checking
1864 // the initial data saver status here is superfluous because the intent won't
1865 // be sent until the system is ready.
1866 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
1867 final IntentFilter dataSaverIntentFilter =
1868 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
1869 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
1870 null /* broadcastPermission */, mHandler);
1871 }
1872
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001873 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1874 // But reading the trunk stable flags from mainline modules is not supported yet.
1875 // So enabling this feature on V+ release.
1876 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1877 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1878 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001879
Chalard Jean46bfbf02022-02-02 00:56:25 +09001880 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001881 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001882 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001883 } catch (RemoteException | ServiceSpecificException e) {
1884 loge("Error registering event listener :" + e);
1885 }
1886
Erik Kline05f2b402015-04-30 12:58:40 +09001887 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1888 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001889
chiachangwang7c17c282023-02-02 05:58:59 +00001890 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001891 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001892 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001893
1894 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001895 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001896 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1897 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001898 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001899 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1900 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001901
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001902 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001903 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001904 mNetworkRanker =
1905 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1906
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001907 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001908
Chiachang Wangc1215d32020-10-20 15:38:58 +08001909 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001910 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001911
Chalard Jean28018572020-12-21 18:36:52 +09001912 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1913 // request that doesn't allow fallback to the default network. It should never be visible
1914 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1915 // arguments like the handler or the DnsResolver.
1916 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001917 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001918 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001919 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001920 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001921 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001922 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1923 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001924
1925 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001926 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1927 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1928 // Even if it could, running on S would at least require mocking out the BPF map,
1929 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1930 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001931 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001932 mDscpPolicyTracker = new DscpPolicyTracker();
1933 }
Tyler Wear72388212021-09-09 14:49:02 -07001934 } catch (ErrnoException e) {
1935 loge("Unable to create DscpPolicyTracker");
1936 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001937
1938 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1939 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001940
Chalard Jeandf29a852023-05-29 17:02:43 +09001941 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001942 mCdmps = new CompanionDeviceManagerProxyService(context);
1943 } else {
1944 mCdmps = null;
1945 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001946
Chalard Jean2fb66f12023-08-25 12:50:37 +09001947 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
Yang Sun29037f62023-12-04 10:31:58 +08001948 mMulticastRoutingCoordinatorService =
1949 mDeps.makeMulticastRoutingCoordinatorService(mHandler);
Chalard Jean2fb66f12023-08-25 12:50:37 +09001950
Motomu Utsumi701efff2024-02-13 12:46:59 +09001951 mDestroyFrozenSockets = mDeps.isAtLeastV() || (mDeps.isAtLeastU()
1952 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION));
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001953 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1954 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001955 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1956 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001957 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001958 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1959 new UidFrozenStateChangedCallback() {
1960 @Override
1961 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1962 if (uids.length != frozenStates.length) {
1963 Log.wtf(TAG, "uids has length " + uids.length
1964 + " but frozenStates has length " + frozenStates.length);
1965 return;
1966 }
1967
1968 final UidFrozenStateChangedArgs args =
1969 new UidFrozenStateChangedArgs(uids, frozenStates);
1970
1971 mHandler.sendMessage(
1972 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1973 }
1974 };
1975
1976 final ActivityManager activityManager =
1977 mContext.getSystemService(ActivityManager.class);
1978 activityManager.registerUidFrozenStateChangedCallback(
1979 (Runnable r) -> r.run(), frozenStateChangedCallback);
1980 }
Yuyang Huang41557552023-11-28 12:47:22 +09001981
1982 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
1983 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
1984 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001985 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001986
Xiao Ma0a171c02022-01-23 16:14:51 +00001987 /**
1988 * Check whether or not the device supports Ethernet transport.
1989 */
1990 public static boolean deviceSupportsEthernet(final Context context) {
1991 final PackageManager pm = context.getPackageManager();
1992 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1993 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1994 }
1995
Chalard Jean46adcf32018-04-18 20:18:38 +09001996 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001997 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1998 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001999 }
2000
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002001 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
2002 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09002003 final NetworkCapabilities netCap = new NetworkCapabilities();
2004 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002005 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09002006 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002007 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09002008 return netCap;
2009 }
2010
James Mattis45d81842021-01-10 14:24:24 -08002011 private NetworkRequest createDefaultRequest() {
2012 return createDefaultInternetRequestForTransport(
2013 TYPE_NONE, NetworkRequest.Type.REQUEST);
2014 }
2015
lucaslin3ba7cc22022-12-19 02:35:33 +00002016 private NetworkRequest createVpnRequest() {
2017 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
2018 .withoutDefaultCapabilities()
2019 .addTransportType(TRANSPORT_VPN)
2020 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
2021 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
2022 .build();
2023 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2024 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
2025 }
2026
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09002027 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002028 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09002029 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09002030 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002031 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08002032 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08002033 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09002034 netCap.addTransportType(transportType);
2035 }
James Mattis45d81842021-01-10 14:24:24 -08002036 return createNetworkRequest(type, netCap);
2037 }
2038
2039 private NetworkRequest createNetworkRequest(
2040 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002041 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09002042 }
2043
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002044 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
2045 NetworkRequest.Type type) {
2046 final NetworkCapabilities netCap = new NetworkCapabilities();
2047 netCap.clearAll();
2048 netCap.addCapability(capability);
2049 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2050 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
2051 }
2052
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002053 // Used only for testing.
2054 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07002055 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002056 // changing ContentResolver to make registerContentObserver non-final).
2057 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
2058 // by subclassing SettingsObserver.
2059 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002060 void updateAlwaysOnNetworks() {
2061 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002062 }
2063
Erik Kline9a62f012018-03-21 07:18:33 -07002064 // See FakeSettingsProvider comment above.
2065 @VisibleForTesting
2066 void updatePrivateDnsSettings() {
2067 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
2068 }
2069
paulhu51f77dc2021-06-07 02:34:20 +00002070 @VisibleForTesting
2071 void updateMobileDataPreferredUids() {
2072 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
2073 }
2074
Patrick Rohr2857ac42022-01-21 14:58:16 +01002075 @VisibleForTesting
2076 void updateIngressRateLimit() {
2077 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
2078 }
2079
Aaron Huang40b52442021-06-08 04:34:24 +08002080 @VisibleForTesting
2081 void simulateUpdateProxyInfo(@Nullable final Network network,
2082 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08002083 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08002084 new Pair<>(network, proxyInfo)).sendToTarget();
2085 }
2086
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00002087 /**
2088 * Called when satellite network fallback uids at {@link SatelliteAccessController}
2089 * cache was updated based on {@link
2090 * android.app.role.OnRoleHoldersChangedListener#onRoleHoldersChanged(String, UserHandle)},
2091 * to create multilayer request with preference order
2092 * {@link #PREFERENCE_ORDER_SATELLITE_FALLBACK} there on.
2093 *
2094 */
2095 private void updateSatelliteNetworkPreferenceUids(Set<Integer> satelliteNetworkFallbackUids) {
2096 handleSetSatelliteNetworkPreference(satelliteNetworkFallbackUids);
2097 }
2098
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002099 private void handleAlwaysOnNetworkRequest(
2100 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002101 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002102 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002103 handleAlwaysOnNetworkRequest(networkRequest, enable);
2104 }
2105
2106 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002107 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002108 if (enable == isEnabled) {
2109 return; // Nothing to do.
2110 }
2111
2112 if (enable) {
2113 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002114 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002115 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002116 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002117 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002118 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2119 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002120 }
2121 }
2122
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002123 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002124 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2125 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2126 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2127 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002128 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2129 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002130 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002131 }
2132
paulhu51f77dc2021-06-07 02:34:20 +00002133 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002134 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002135 private void registerSettingsCallbacks() {
2136 // Watch for global HTTP proxy changes.
2137 mSettingsObserver.observe(
2138 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2139 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2140
Chalard Jean46bfbf02022-02-02 00:56:25 +09002141 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002142 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002143 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002144 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2145
Chalard Jean46bfbf02022-02-02 00:56:25 +09002146 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002147 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002148 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002149 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002150
2151 // Watch for mobile data preferred uids changes.
2152 mSettingsObserver.observe(
2153 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2154 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002155
2156 // Watch for ingress rate limit changes.
2157 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002158 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002159 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2160 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002161 }
2162
Erik Kline31b4a9e2018-01-11 21:07:29 +09002163 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002164 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2165 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002166 }
2167 }
2168
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002169 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002170 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2171 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002172 return mNextNetworkRequestId++;
2173 }
2174
junyulai74f9a8b2018-06-13 15:00:37 +08002175 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002176 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002177 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002178 if (network == null) {
2179 return null;
2180 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002181 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002182 }
2183
2184 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002185 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002186 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002187 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002188 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002189
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002190 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002191 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002192 private NetworkAgentInfo getVpnForUid(int uid) {
2193 synchronized (mNetworkForNetId) {
2194 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2195 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002196 if (nai.isVPN() && nai.everConnected()
2197 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002198 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002199 }
2200 }
2201 }
2202 return null;
2203 }
2204
Chalard Jean46bfbf02022-02-02 00:56:25 +09002205 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002206 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002207 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002208 final NetworkAgentInfo nai = getVpnForUid(uid);
2209 if (nai != null) return nai.declaredUnderlyingNetworks;
2210 return null;
2211 }
2212
Lorenzo Colittia7574052021-01-19 01:33:05 +09002213 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002214 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002215
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002216 final Network[] networks = getVpnUnderlyingNetworks(uid);
2217 if (networks != null) {
2218 // getUnderlyingNetworks() returns:
2219 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2220 // empty array => the VPN explicitly said "no default network".
2221 // non-empty array => the VPN specified one or more default networks; we use the
2222 // first one.
2223 if (networks.length > 0) {
2224 nai = getNetworkAgentInfoForNetwork(networks[0]);
2225 } else {
2226 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002227 }
2228 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002229 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002230 }
2231
2232 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002233 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002234 */
paulhu7aeba372020-12-30 00:42:19 +08002235 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2236 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002237 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002238 if (ignoreBlocked) {
2239 return false;
2240 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002241 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002242 final long ident = Binder.clearCallingIdentity();
2243 try {
2244 final boolean metered = nc == null ? true : nc.isMetered();
2245 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2246 } finally {
2247 Binder.restoreCallingIdentity(ident);
2248 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002249 }
2250
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002251 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002252 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2253 return;
2254 }
Hugo Benichi47011212017-03-30 10:46:05 +09002255 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002256 synchronized (mBlockedAppUids) {
2257 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002258 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002259 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002260 blocked = false;
2261 } else {
2262 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002263 }
2264 }
Hugo Benichi47011212017-03-30 10:46:05 +09002265 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2266 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2267 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002268 }
2269
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002270 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002271 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2272 return;
2273 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002274 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002275 final int requestId = nri.getActiveRequest() != null
2276 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002277 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002278 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002279 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002280 }
2281
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002282 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002283 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002284 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002285 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002286 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002287 @NonNull
2288 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2289 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002290 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2291 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2292 // but only exists if an app asks about them or requests them. Ensure the requesting app
2293 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002294 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002295 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2296 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2297 null /* extraInfo */);
2298 }
2299 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002300 return filtered;
2301 }
2302
2303 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2304 boolean ignoreBlocked) {
2305 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2306 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002307 }
2308
2309 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002310 * Return NetworkInfo for the active (i.e., connected) network interface.
2311 * It is assumed that at most one network is active at a time. If more
2312 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002313 * @return the info for the active network, or {@code null} if none is
2314 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002315 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002316 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002317 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002318 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002319 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002320 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002321 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2322 if (nai == null) return null;
2323 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2324 maybeLogBlockedNetworkInfo(networkInfo, uid);
2325 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002326 }
2327
Paul Jensen1f567382015-02-13 14:18:39 -05002328 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002329 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002330 public Network getActiveNetwork() {
2331 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002332 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002333 }
2334
2335 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002336 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002337 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002338 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002339 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002340 }
2341
Chalard Jean46bfbf02022-02-02 00:56:25 +09002342 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002343 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002344 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2345 if (vpnNai != null) {
2346 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2347 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2348 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002349 }
Paul Jensen1f567382015-02-13 14:18:39 -05002350 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002351
James Mattis2516da32021-01-31 17:06:19 -08002352 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002353 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2354 ignoreBlocked)) {
2355 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002356 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002357 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002358 }
2359
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002360 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002361 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002362 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002363 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002364 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2365 if (nai == null) return null;
2366 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002367 }
2368
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002369 /** Returns a NetworkInfo object for a network that doesn't exist. */
2370 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2371 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2372 getNetworkTypeName(networkType), "" /* subtypeName */);
2373 info.setIsAvailable(true);
2374 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2375 // background data is restricted.
2376 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2377 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2378 ? DetailedState.BLOCKED
2379 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002380 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2381 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002382 return info;
2383 }
2384
Lorenzo Colittia7574052021-01-19 01:33:05 +09002385 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002386 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2387 return null;
2388 }
2389 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002390 if (nai == null) {
2391 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002392 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002393 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2394 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002395 }
2396
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002397 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002398 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002399 public NetworkInfo getNetworkInfo(int networkType) {
2400 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002401 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002402 if (getVpnUnderlyingNetworks(uid) != null) {
2403 // A VPN is active, so we may need to return one of its underlying networks. This
2404 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002405 // getNetworkAgentInfoForUid.
2406 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2407 if (nai == null) return null;
2408 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2409 if (networkInfo.getType() == networkType) {
2410 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002411 }
2412 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002413 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002414 }
2415
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002416 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002417 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002418 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002419 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002420 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002421 if (nai == null) return null;
2422 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002423 }
2424
2425 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002426 public NetworkInfo[] getAllNetworkInfo() {
2427 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002428 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002429 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2430 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002431 NetworkInfo info = getNetworkInfo(networkType);
2432 if (info != null) {
2433 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002434 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002435 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002436 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002437 }
2438
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002439 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002440 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002441 public Network getNetworkForType(int networkType) {
2442 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002443 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2444 return null;
2445 }
2446 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2447 if (nai == null) {
2448 return null;
2449 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002450 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002451 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2452 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002453 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002454 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002455 }
2456
2457 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002458 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002459 public Network[] getAllNetworks() {
2460 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002461 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002462 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002463 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002464 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002465 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002466 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002467 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002468 }
2469
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002470 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002471 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002472 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002473 // The basic principle is: if an app's traffic could possibly go over a
2474 // network, without the app doing anything multinetwork-specific,
2475 // (hence, by "default"), then include that network's capabilities in
2476 // the array.
2477 //
2478 // In the normal case, app traffic only goes over the system's default
2479 // network connection, so that's the only network returned.
2480 //
2481 // With a VPN in force, some app traffic may go into the VPN, and thus
2482 // over whatever underlying networks the VPN specifies, while other app
2483 // traffic may go over the system default network (e.g.: a split-tunnel
2484 // VPN, or an app disallowed by the VPN), so the set of networks
2485 // returned includes the VPN's underlying networks and the system
2486 // default.
2487 enforceAccessPermission();
2488
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002489 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002490
James Mattis2516da32021-01-31 17:06:19 -08002491 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2492 if (!nri.isBeingSatisfied()) {
2493 continue;
2494 }
2495 final NetworkAgentInfo nai = nri.getSatisfier();
2496 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2497 if (null != nc
2498 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2499 && !result.containsKey(nai.network)) {
2500 result.put(
2501 nai.network,
2502 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002503 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002504 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2505 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002506 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002507 }
2508
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002509 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002510 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002511 if (null != networks) {
2512 for (final Network network : networks) {
2513 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2514 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002515 result.put(
2516 network,
2517 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002518 nc,
2519 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002520 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002521 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002522 }
2523 }
2524 }
2525
2526 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2527 out = result.values().toArray(out);
2528 return out;
2529 }
2530
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002531 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2532 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2533 // can call sampleConnectivityState and make the checks on it.
2534 @NonNull
2535 private StatsEvent sampleConnectivityStateToStatsEvent() {
2536 final ConnectivityStateSample sample = sampleConnectivityState();
2537 return ConnectivityStatsLog.buildStatsEvent(
2538 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2539 sample.getNetworkCountPerTransports().toByteArray(),
2540 sample.getConnectionDurationPerTransports().toByteArray(),
2541 sample.getNetworkRequestCount().toByteArray(),
2542 sample.getNetworks().toByteArray());
2543 }
2544
2545 /**
2546 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2547 *
2548 * This is used for metrics. These snapshots will be sampled and constitute a base for
2549 * statistics about connectivity state of devices.
2550 */
2551 @VisibleForTesting
2552 @NonNull
2553 public ConnectivityStateSample sampleConnectivityState() {
2554 ensureRunningOnConnectivityServiceThread();
2555 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2556 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2557 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2558 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2559 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2560 return builder.build();
2561 }
2562
2563 private static NetworkCountPerTransports sampleNetworkCount(
2564 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2565 final SparseIntArray countPerTransports = new SparseIntArray();
2566 for (final NetworkAgentInfo nai : nais) {
2567 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2568 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2569 }
2570 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2571 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2572 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2573 c.setTransportTypes(countPerTransports.keyAt(i));
2574 c.setNetworkCount(countPerTransports.valueAt(i));
2575 builder.addNetworkCountForTransports(c);
2576 }
2577 return builder.build();
2578 }
2579
2580 private static ConnectionDurationPerTransports sampleConnectionDuration(
2581 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2582 final ConnectionDurationPerTransports.Builder builder =
2583 ConnectionDurationPerTransports.newBuilder();
2584 for (final NetworkAgentInfo nai : nais) {
2585 final ConnectionDurationForTransports.Builder c =
2586 ConnectionDurationForTransports.newBuilder();
2587 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2588 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2589 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2590 // Add millisPerSecond/2 to round up or down to the nearest value
2591 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2592 builder.addConnectionDurationForTransports(c);
2593 }
2594 return builder.build();
2595 }
2596
2597 private static NetworkRequestCount sampleNetworkRequestCount(
2598 @NonNull final Collection<NetworkRequestInfo> nris) {
2599 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2600 final SparseIntArray countPerType = new SparseIntArray();
2601 for (final NetworkRequestInfo nri : nris) {
2602 final int type;
2603 if (Process.SYSTEM_UID == nri.mAsUid) {
2604 // The request is filed "as" the system, so it's the system on its own behalf.
2605 type = RequestType.RT_SYSTEM.getNumber();
2606 } else if (Process.SYSTEM_UID == nri.mUid) {
2607 // The request is filed by the system as some other app, so it's the system on
2608 // behalf of an app.
2609 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2610 } else {
2611 // Not the system, so it's an app requesting on its own behalf.
2612 type = RequestType.RT_APP.getNumber();
2613 }
2614 countPerType.put(type, countPerType.get(type, 0));
2615 }
2616 for (int i = countPerType.size() - 1; i >= 0; --i) {
2617 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2618 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2619 r.setRequestCount(countPerType.valueAt(i));
2620 builder.addRequestCountForType(r);
2621 }
2622 return builder.build();
2623 }
2624
2625 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2626 final NetworkList.Builder builder = NetworkList.newBuilder();
2627 for (final NetworkAgentInfo nai : nais) {
2628 final NetworkCapabilities nc = nai.networkCapabilities;
2629 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2630 d.setTransportTypes((int) nc.getTransportTypesInternal());
2631 final MeteredState meteredState;
2632 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2633 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2634 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2635 meteredState = MeteredState.METERED_NO;
2636 } else {
2637 meteredState = MeteredState.METERED_YES;
2638 }
2639 d.setMeteredState(meteredState);
2640 final ValidatedState validatedState;
2641 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2642 validatedState = ValidatedState.VS_PORTAL;
2643 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2644 validatedState = ValidatedState.VS_PARTIAL;
2645 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2646 validatedState = ValidatedState.VS_VALID;
2647 } else {
2648 validatedState = ValidatedState.VS_INVALID;
2649 }
2650 d.setValidatedState(validatedState);
2651 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2652 d.setCapabilities(nc.getCapabilitiesInternal());
2653 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2654 builder.addNetworkDescription(d);
2655 }
2656 return builder.build();
2657 }
2658
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002659 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002660 public boolean isNetworkSupported(int networkType) {
2661 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002662 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002663 }
2664
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002665 /**
2666 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002667 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002668 * @return the ip properties for the active network, or {@code null} if
2669 * none is active
2670 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002671 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002672 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002673 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002674 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002675 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2676 if (nai == null) return null;
2677 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002678 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002679 }
2680
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002681 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002682 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002683 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002684 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002685 final LinkProperties lp = getLinkProperties(nai);
2686 if (lp == null) return null;
2687 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002688 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002689 }
2690
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002691 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002692 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002693 public LinkProperties getLinkProperties(Network network) {
2694 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002695 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2696 if (lp == null) return null;
2697 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002698 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002699 }
2700
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002701 @Nullable
2702 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002703 if (nai == null) {
2704 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002705 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002706 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002707 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002708 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002709 }
2710
lucaslinc582d502022-01-27 09:07:00 +08002711 @Override
2712 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002713 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002714 @NonNull String packageName, @Nullable String callingAttributionTag) {
2715 Objects.requireNonNull(packageName);
2716 Objects.requireNonNull(lp);
2717 enforceNetworkStackOrSettingsPermission();
Junyu Lai71b51532024-02-01 10:39:01 +08002718 if (!hasAccessPermission(-1 /* pid */, uid)) {
lucaslinc582d502022-01-27 09:07:00 +08002719 return null;
2720 }
2721 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2722 }
2723
Qingxi Lib2748102020-01-08 12:51:49 -08002724 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2725 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2726 }
2727
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002728 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002729 if (nai == null) return null;
2730 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002731 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002732 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002733 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002734 }
2735
2736 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002737 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2738 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002739 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002740 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002741 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002742 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002743 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002744 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002745 }
2746
lucaslinc582d502022-01-27 09:07:00 +08002747 @Override
lucaslind2b06132022-03-02 10:56:57 +08002748 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2749 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2750 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002751 Objects.requireNonNull(nc);
2752 Objects.requireNonNull(packageName);
2753 enforceNetworkStackOrSettingsPermission();
Junyu Lai71b51532024-02-01 10:39:01 +08002754 if (!hasAccessPermission(-1 /* pid */, uid)) {
lucaslinc582d502022-01-27 09:07:00 +08002755 return null;
2756 }
2757 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2758 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2759 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2760 callingAttributionTag);
2761 }
2762
lucaslin69e1aa92022-03-22 18:15:09 +08002763 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2764 if (nc.getUnderlyingNetworks() != null
Junyu Lai71b51532024-02-01 10:39:01 +08002765 && !hasNetworkFactoryOrSettingsPermission(pid, uid)) {
lucaslin69e1aa92022-03-22 18:15:09 +08002766 nc.setUnderlyingNetworks(null);
2767 }
2768 }
2769
Chalard Jean53017782022-11-24 17:13:44 +09002770 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
2771 return Process.SYSTEM_UID == uid
Junyu Lai71b51532024-02-01 10:39:01 +08002772 || hasAnyPermissionOf(mContext, pid, uid,
Chalard Jean53017782022-11-24 17:13:44 +09002773 android.Manifest.permission.NETWORK_FACTORY);
2774 }
2775
Qingxi Libb8da982020-01-17 17:54:27 -08002776 @VisibleForTesting
2777 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002778 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002779 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2780 // this would be expensive (one more permission check every time any NC callback is
2781 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2782 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2783 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002784 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Junyu Lai71b51532024-02-01 10:39:01 +08002785 if (!hasSettingsPermission(callerPid, callerUid)) {
Chalard Jean46adcf32018-04-18 20:18:38 +09002786 newNc.setUids(null);
2787 newNc.setSSID(null);
2788 }
Etan Cohen107ae952018-12-30 17:59:59 -08002789 if (newNc.getNetworkSpecifier() != null) {
2790 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2791 }
Junyu Lai71b51532024-02-01 10:39:01 +08002792 if (!hasAnyPermissionOf(mContext, callerPid, callerUid,
Junyu Lai4c6fe232023-04-11 11:33:46 +08002793 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002794 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2795 newNc.setAdministratorUids(new int[0]);
2796 }
Chalard Jean53017782022-11-24 17:13:44 +09002797 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09002798 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002799 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002800 }
lucaslin69e1aa92022-03-22 18:15:09 +08002801 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002802
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002803 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002804 }
2805
Roshan Pius98f59ec2021-02-23 08:47:39 -08002806 /**
2807 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002808 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002809 * NetworkCapabilities.
2810 * Note: This wrapper does not support any sort of invalidation and thus must not be
2811 * persistent or long-lived. It may only be used for the time necessary to
2812 * compute the redactions required by one particular NetworkCallback or
2813 * synchronous call.
2814 */
2815 private class RedactionPermissionChecker {
2816 private final int mCallingPid;
2817 private final int mCallingUid;
2818 @NonNull private final String mCallingPackageName;
2819 @Nullable private final String mCallingAttributionTag;
2820
2821 private Boolean mHasLocationPermission = null;
2822 private Boolean mHasLocalMacAddressPermission = null;
2823 private Boolean mHasSettingsPermission = null;
2824
2825 RedactionPermissionChecker(int callingPid, int callingUid,
2826 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2827 mCallingPid = callingPid;
2828 mCallingUid = callingUid;
2829 mCallingPackageName = callingPackageName;
2830 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002831 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002832
2833 private boolean hasLocationPermissionInternal() {
2834 final long token = Binder.clearCallingIdentity();
2835 try {
2836 return mLocationPermissionChecker.checkLocationPermission(
2837 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2838 null /* message */);
2839 } finally {
2840 Binder.restoreCallingIdentity(token);
2841 }
2842 }
2843
2844 /**
2845 * Returns whether the app holds location permission or not (might return cached result
2846 * if the permission was already checked before).
2847 */
2848 public boolean hasLocationPermission() {
2849 if (mHasLocationPermission == null) {
2850 // If there is no cached result, perform the check now.
2851 mHasLocationPermission = hasLocationPermissionInternal();
2852 }
2853 return mHasLocationPermission;
2854 }
2855
2856 /**
2857 * Returns whether the app holds local mac address permission or not (might return cached
2858 * result if the permission was already checked before).
2859 */
Junyu Lai71b51532024-02-01 10:39:01 +08002860 @CheckResult
Roshan Pius98f59ec2021-02-23 08:47:39 -08002861 public boolean hasLocalMacAddressPermission() {
2862 if (mHasLocalMacAddressPermission == null) {
2863 // If there is no cached result, perform the check now.
Junyu Lai71b51532024-02-01 10:39:01 +08002864 mHasLocalMacAddressPermission = ConnectivityService.this
2865 .hasLocalMacAddressPermission(mCallingPid, mCallingUid);
Roshan Pius98f59ec2021-02-23 08:47:39 -08002866 }
2867 return mHasLocalMacAddressPermission;
2868 }
2869
2870 /**
2871 * Returns whether the app holds settings permission or not (might return cached
2872 * result if the permission was already checked before).
2873 */
Junyu Lai71b51532024-02-01 10:39:01 +08002874 @CheckResult
Roshan Pius98f59ec2021-02-23 08:47:39 -08002875 public boolean hasSettingsPermission() {
2876 if (mHasSettingsPermission == null) {
2877 // If there is no cached result, perform the check now.
Junyu Lai71b51532024-02-01 10:39:01 +08002878 mHasSettingsPermission =
2879 ConnectivityService.this.hasSettingsPermission(mCallingPid, mCallingUid);
Roshan Pius98f59ec2021-02-23 08:47:39 -08002880 }
2881 return mHasSettingsPermission;
2882 }
2883 }
2884
2885 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2886 @NetworkCapabilities.NetCapability long redaction) {
2887 return (redactions & redaction) != 0;
2888 }
2889
2890 /**
2891 * Use the provided |applicableRedactions| to check the receiving app's
2892 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2893 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2894 * before being sent to the corresponding app.
2895 */
2896 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2897 @NetworkCapabilities.RedactionType long applicableRedactions,
2898 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2899 boolean includeLocationSensitiveInfo) {
2900 long redactions = applicableRedactions;
2901 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2902 if (includeLocationSensitiveInfo
2903 && redactionPermissionChecker.hasLocationPermission()) {
2904 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2905 }
2906 }
2907 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2908 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2909 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2910 }
2911 }
2912 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2913 if (redactionPermissionChecker.hasSettingsPermission()) {
2914 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2915 }
2916 }
2917 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002918 }
2919
Qingxi Lib2748102020-01-08 12:51:49 -08002920 @VisibleForTesting
2921 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002922 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002923 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002924 int callingPid, int callingUid, @NonNull String callingPkgName,
2925 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002926 if (nc == null) {
2927 return null;
2928 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002929 // Avoid doing location permission check if the transport info has no location sensitive
2930 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002931 final RedactionPermissionChecker redactionPermissionChecker =
2932 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2933 callingAttributionTag);
2934 final long redactions = retrieveRequiredRedactions(
2935 nc.getApplicableRedactions(), redactionPermissionChecker,
2936 includeLocationSensitiveInfo);
2937 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002938 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002939 // TODO : calling UID is redacted because apps should generally not know what UID is
2940 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002941 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002942 newNc.setOwnerUid(INVALID_UID);
2943 return newNc;
2944 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002945 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2946 if (nc.hasTransport(TRANSPORT_VPN)) {
2947 // Owner UIDs already checked above. No need to re-check.
2948 return newNc;
2949 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002950 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2951 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002952 // compatibility for older apps.
2953 if (!includeLocationSensitiveInfo
2954 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002955 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002956 newNc.setOwnerUid(INVALID_UID);
2957 return newNc;
2958 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002959 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002960 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002961 newNc.setOwnerUid(INVALID_UID);
2962 }
Qingxi Lib2748102020-01-08 12:51:49 -08002963 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002964 }
2965
lucaslinc582d502022-01-27 09:07:00 +08002966 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002967 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2968 LinkProperties lp, int callerPid, int callerUid) {
2969 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002970 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2971 // this would be expensive (one more permission check every time any LP callback is
2972 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2973 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2974 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002975
2976 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2977 final boolean needsSanitization =
2978 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2979 if (!needsSanitization) {
2980 return new LinkProperties(lp);
2981 }
2982
Junyu Lai71b51532024-02-01 10:39:01 +08002983 if (hasSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002984 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002985 }
2986
2987 final LinkProperties newLp = new LinkProperties(lp);
2988 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2989 // object gets parceled.
2990 newLp.setCaptivePortalApiUrl(null);
2991 newLp.setCaptivePortalData(null);
2992 return newLp;
2993 }
2994
Roshan Pius08c94fb2020-01-16 12:17:17 -08002995 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2996 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002997 // There is no need to track the effective UID of the request here. If the caller
2998 // lacks the settings permission, the effective UID is the same as the calling ID.
Junyu Lai71b51532024-02-01 10:39:01 +08002999 if (!hasSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003000 // Unprivileged apps can only pass in null or their own UID.
3001 if (nc.getUids() == null) {
3002 // If the caller passes in null, the callback will also match networks that do not
3003 // apply to its UID, similarly to what it would see if it called getAllNetworks.
3004 // In this case, redact everything in the request immediately. This ensures that the
3005 // app is not able to get any redacted information by filing an unredacted request
3006 // and observing whether the request matches something.
3007 if (nc.getNetworkSpecifier() != null) {
3008 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
3009 }
3010 } else {
3011 nc.setSingleUid(callerUid);
3012 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09003013 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08003014 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07003015 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08003016
3017 // Clear owner UID; this can never come from an app.
3018 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003019 }
3020
Chalard Jean38354d12018-03-20 19:13:57 +09003021 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003022 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09003023 nc.addCapability(NET_CAPABILITY_FOREGROUND);
3024 }
3025 }
3026
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09003027 @Override
3028 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
3029 enforceAccessPermission();
3030 final int callerUid = Binder.getCallingUid();
3031 final long token = Binder.clearCallingIdentity();
3032 try {
3033 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
3034 } finally {
3035 Binder.restoreCallingIdentity(token);
3036 }
3037 }
3038
junyulaiebd15162021-03-03 12:09:05 +08003039 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003040 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07003041 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08003042 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08003043 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08003044
Serik Beketayev05130302021-01-15 16:47:25 -08003045 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08003046 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08003047 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
3048 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08003049 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08003050 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08003051 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08003052 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
3053 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07003054 }
3055 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09003056 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07003057 }
3058
Jeff Sharkey66fa9682011-08-02 17:22:34 -07003059 @Override
junyulaiebd15162021-03-03 12:09:05 +08003060 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08003061 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08003062 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08003063 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08003064
3065 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
3066 for (Network network : getAllNetworks()) {
3067 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09003068 final boolean includeNetwork = (nai != null) && nai.isCreated();
3069 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08003070 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
3071 // NetworkCapabilities, which may contain UIDs of apps to which the
3072 // network applies. Should the UIDs be cleared so as not to leak or
3073 // interfere ?
3074 result.add(nai.getNetworkStateSnapshot());
3075 }
3076 }
3077 return result;
3078 }
3079
3080 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003081 public boolean isActiveNetworkMetered() {
3082 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003083
Qingxi Lib2748102020-01-08 12:51:49 -08003084 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06003085 if (caps != null) {
3086 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3087 } else {
3088 // Always return the most conservative value
3089 return true;
3090 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07003091 }
3092
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003093 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09003094 * Ensures that the system cannot call a particular method.
3095 */
3096 private boolean disallowedBecauseSystemCaller() {
3097 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07003098 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
3099 // for devices launched with Q and above. However, existing devices upgrading to Q and
3100 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003101 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07003102 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003103 log("This method exists only for app backwards compatibility"
3104 + " and must not be called by system services.");
3105 return true;
3106 }
3107 return false;
3108 }
3109
3110 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003111 * Ensure that a network route exists to deliver traffic to the specified
3112 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003113 * @param networkType the type of the network over which traffic to the
3114 * specified host is to be routed
3115 * @param hostAddress the IP address of the host to which the route is
3116 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003117 * @return {@code true} on success, {@code false} on failure
3118 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003119 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003120 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3121 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003122 if (disallowedBecauseSystemCaller()) {
3123 return false;
3124 }
Junyu Lai8fdc4312024-01-16 11:19:43 +08003125 PermissionUtils.enforcePackageNameMatchesUid(
3126 mContext, mDeps.getCallingUid(), callingPackageName);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003127 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003128 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003129 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003130 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003131
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003132 InetAddress addr;
3133 try {
3134 addr = InetAddress.getByAddress(hostAddress);
3135 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003136 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003137 return false;
3138 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003139
The Android Open Source Project28527d22009-03-03 19:31:44 -08003140 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003141 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003142 return false;
3143 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003144
3145 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3146 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003147 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003148 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3149 } else {
3150 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3151 }
3152 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003153 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003154
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003155 DetailedState netState;
3156 synchronized (nai) {
3157 netState = nai.networkInfo.getDetailedState();
3158 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003159
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003160 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003161 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003162 log("requestRouteToHostAddress on down network "
3163 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003164 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003165 }
3166 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003167 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003168
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003169 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003170 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003171 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003172 LinkProperties lp;
3173 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003174 synchronized (nai) {
3175 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003176 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003177 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003178 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003179 if (DBG) {
3180 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3181 }
Wink Saville32506bc2013-06-29 21:10:57 -07003182 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003183 } finally {
3184 Binder.restoreCallingIdentity(token);
3185 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003186 }
3187
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003188 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003189 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003190 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003191 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003192 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003193 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003194 if (bestRoute.getGateway().equals(addr)) {
3195 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003196 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003197 } else {
3198 // if we will connect to this through another route, add a direct route
3199 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003200 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003201 }
3202 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003203 if (DBG) log("Adding legacy route " + bestRoute +
3204 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003205
3206 final String dst = bestRoute.getDestinationLinkAddress().toString();
3207 final String nextHop = bestRoute.hasGateway()
3208 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003209 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003210 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3211 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003212 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003213 return false;
3214 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003215 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003216 }
3217
paulhu7c0a2e62021-01-08 00:51:49 +08003218 class DnsResolverUnsolicitedEventCallback extends
3219 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003220 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003221 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003222 try {
3223 mHandler.sendMessage(mHandler.obtainMessage(
3224 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003225 new PrivateDnsValidationUpdate(event.netId,
3226 InetAddresses.parseNumericAddress(event.ipAddress),
3227 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003228 } catch (IllegalArgumentException e) {
3229 loge("Error parsing ip address in validation event");
3230 }
3231 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003232
3233 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003234 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3235 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003236 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3237 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3238 // event callback for certain nai. e.g. cellular. Register here to pass to
3239 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003240 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003241 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3242 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003243 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003244 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003245 }
3246 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003247
3248 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003249 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3250 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3251 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003252 }
dalyk1720e542018-03-05 12:42:22 -05003253
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003254 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003255 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003256 return this.VERSION;
3257 }
3258
3259 @Override
3260 public String getInterfaceHash() {
3261 return this.HASH;
3262 }
paulhu7c0a2e62021-01-08 00:51:49 +08003263 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003264
3265 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003266 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3267 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003268
paulhu7c0a2e62021-01-08 00:51:49 +08003269 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003270 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003271 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003272 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003273 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003274 }
3275 }
3276
Sudheer Shanka9967d462021-03-18 19:09:25 +00003277 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003278 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003279 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003280 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3281 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003282 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003283 };
3284
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003285 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003286 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003287 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003288 }
3289
Mark Fasheh7c999d82023-05-04 20:23:11 +00003290 static final class UidFrozenStateChangedArgs {
3291 final int[] mUids;
3292 final int[] mFrozenStates;
3293
3294 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3295 mUids = uids;
3296 mFrozenStates = frozenStates;
3297 }
3298 }
3299
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003300 /**
3301 * Check if the cell network is idle.
3302 * @return true if the cell network state is idle
3303 * false if the cell network state is active or unknown
3304 */
3305 private boolean isCellNetworkIdle() {
3306 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3307 if (defaultNai == null
3308 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3309 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3310 // cell network is not the default network, cell network state is unknown.
3311 // TODO(b/279380356): Track cell network state when the cell is not the default network
3312 return false;
3313 }
3314
3315 return !mNetworkActivityTracker.isDefaultNetworkActive();
3316 }
3317
Mark Fasheh7c999d82023-05-04 20:23:11 +00003318 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003319 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003320
3321 for (int i = 0; i < uids.length; i++) {
3322 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003323 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003324 } else {
3325 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003326 }
3327 }
3328
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003329 if (ownerUids.isEmpty()) {
3330 return;
3331 }
3332
3333 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3334 // Delay closing sockets to avoid waking the cell modem up.
3335 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3336 // than waking cell modem up.
3337 mPendingFrozenUids.addAll(ownerUids);
3338 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003339 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003340 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003341 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003342 loge("Exception in socket destroy: " + e);
3343 }
3344 }
3345 }
3346
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003347 private void closePendingFrozenSockets() {
3348 ensureRunningOnConnectivityServiceThread();
3349
3350 try {
3351 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3352 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3353 loge("Failed to close pending frozen app sockets: " + e);
3354 }
3355 mPendingFrozenUids.clear();
3356 }
3357
3358 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3359 mNetworkActivityTracker.handleReportNetworkActivity(params);
3360
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003361 final boolean isCellNetworkActivity;
3362 if (mTrackMultiNetworkActivities) {
3363 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3364 // nai could be null if netd receives a netlink message and calls the network
3365 // activity change callback after the network is unregistered from ConnectivityService.
3366 isCellNetworkActivity = nai != null
3367 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3368 } else {
3369 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3370 }
3371
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003372 if (mDelayDestroyFrozenSockets
3373 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003374 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003375 && !mPendingFrozenUids.isEmpty()) {
3376 closePendingFrozenSockets();
3377 }
3378 }
3379
3380 /**
3381 * If the cellular network is no longer the default network, close pending frozen sockets.
3382 *
3383 * @param newNetwork new default network
3384 * @param oldNetwork old default network
3385 */
3386 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3387 NetworkAgentInfo oldNetwork) {
3388 final boolean isOldNetworkCellular = oldNetwork != null
3389 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3390 final boolean isNewNetworkCellular = newNetwork != null
3391 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3392
3393 if (isOldNetworkCellular
3394 && !isNewNetworkCellular
3395 && !mPendingFrozenUids.isEmpty()) {
3396 closePendingFrozenSockets();
3397 }
3398 }
3399
3400 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3401 pw.println("CloseFrozenAppSockets:");
3402 pw.increaseIndent();
3403 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3404 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3405 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3406 pw.decreaseIndent();
3407 }
3408
Junyu Lai155760b2023-10-05 14:51:00 +08003409 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3410 pw.println("Bpf Program Status:");
3411 pw.increaseIndent();
3412 try {
3413 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003414 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003415 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003416 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003417 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003418 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003419 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003420 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003421 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003422 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003423 } catch (IOException e) {
3424 pw.println(" IOException");
3425 }
3426 pw.decreaseIndent();
3427 }
3428
Mark Fasheh7c999d82023-05-04 20:23:11 +00003429 @VisibleForTesting
3430 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003431 @VisibleForTesting
3432 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3433 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003434
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003435 @VisibleForTesting
3436 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3437 "allow_sysui_connectivity_reports";
3438
Yuyang Huang41557552023-11-28 12:47:22 +09003439 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
3440
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00003441 public static final String ALLOW_SATALLITE_NETWORK_FALLBACK =
3442 "allow_satallite_network_fallback";
3443
Paul Jensen83f5d572014-08-29 09:54:01 -04003444 private void enforceInternetPermission() {
3445 mContext.enforceCallingOrSelfPermission(
3446 android.Manifest.permission.INTERNET,
3447 "ConnectivityService");
3448 }
3449
The Android Open Source Project28527d22009-03-03 19:31:44 -08003450 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003451 mContext.enforceCallingOrSelfPermission(
3452 android.Manifest.permission.ACCESS_NETWORK_STATE,
3453 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003454 }
3455
Junyu Lai71b51532024-02-01 10:39:01 +08003456 @CheckResult
3457 private boolean hasAccessPermission(int pid, int uid) {
lucaslinc582d502022-01-27 09:07:00 +08003458 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3459 == PERMISSION_GRANTED;
3460 }
3461
paulhua6ee2122021-02-22 15:40:43 +08003462 /**
3463 * Performs a strict and comprehensive check of whether a calling package is allowed to
3464 * change the state of network, as the condition differs for pre-M, M+, and
3465 * privileged/preinstalled apps. The caller is expected to have either the
3466 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3467 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3468 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3469 * permission and cannot be revoked. See http://b/23597341
3470 *
3471 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3472 * of this app will be updated to the current time.
3473 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003474 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003475 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3476 == PackageManager.PERMISSION_GRANTED) {
3477 return;
3478 }
3479
3480 if (callingPkg == null) {
3481 throw new SecurityException("Calling package name is null.");
3482 }
3483
3484 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3485 final int uid = mDeps.getCallingUid();
3486 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3487 callingPkg, callingAttributionTag, null /* message */);
3488
3489 if (mode == AppOpsManager.MODE_ALLOWED) {
3490 return;
3491 }
3492
3493 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3494 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3495 return;
3496 }
3497
3498 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3499 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3500 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003501 }
3502
Charles He9369e612017-05-15 17:07:18 +01003503 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003504 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003505 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003506 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003507 }
3508
Quang Luong98858d62023-02-11 00:25:24 +00003509 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003510 enforceAnyPermissionOf(mContext,
3511 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003512 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003513 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3514 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3515 }
3516
paulhu8e96a752019-08-12 16:25:11 +08003517 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003518 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003519 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003520 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003521 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003522 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003523 }
3524
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003525 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003526 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003527 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003528 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003529 android.Manifest.permission.NETWORK_SETTINGS,
3530 android.Manifest.permission.NETWORK_FACTORY,
3531 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3532 }
3533
3534 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003535 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003536 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003537 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003538 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3539 android.Manifest.permission.NETWORK_FACTORY,
3540 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3541 }
3542
Junyu Lai71b51532024-02-01 10:39:01 +08003543 @CheckResult
3544 private boolean hasNetworkFactoryOrSettingsPermission(int pid, int uid) {
lucaslin69e1aa92022-03-22 18:15:09 +08003545 return PERMISSION_GRANTED == mContext.checkPermission(
3546 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3547 || PERMISSION_GRANTED == mContext.checkPermission(
3548 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3549 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003550 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003551 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003552 }
3553
Junyu Lai71b51532024-02-01 10:39:01 +08003554 @CheckResult
3555 private boolean hasSettingsPermission() {
3556 return hasAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003557 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003558 }
3559
Junyu Lai71b51532024-02-01 10:39:01 +08003560 @CheckResult
3561 private boolean hasSettingsPermission(int pid, int uid) {
Chalard Jean9a396cc2018-02-21 18:43:54 +09003562 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003563 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3564 || PERMISSION_GRANTED == mContext.checkPermission(
3565 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003566 }
3567
paulhu8e96a752019-08-12 16:25:11 +08003568 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003569 enforceNetworkStackPermissionOr(mContext,
3570 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003571 }
3572
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003573 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003574 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003575 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003576 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003577 }
3578
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003579 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003580 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003581 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3582 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003583 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003584 }
3585
James Mattis8378aec2021-01-26 14:05:36 -08003586 private void enforceOemNetworkPreferencesPermission() {
3587 mContext.enforceCallingOrSelfPermission(
3588 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3589 "ConnectivityService");
3590 }
3591
James Mattisfa270db2021-05-31 17:11:10 -07003592 private void enforceManageTestNetworksPermission() {
3593 mContext.enforceCallingOrSelfPermission(
3594 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3595 "ConnectivityService");
3596 }
3597
Junyu Lai71b51532024-02-01 10:39:01 +08003598 @CheckResult
3599 private boolean hasNetworkStackPermission() {
3600 return hasAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003601 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003602 }
3603
Junyu Lai71b51532024-02-01 10:39:01 +08003604 @CheckResult
3605 private boolean hasNetworkStackPermission(int pid, int uid) {
3606 return hasAnyPermissionOf(mContext, pid, uid, android.Manifest.permission.NETWORK_STACK,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003607 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3608 }
3609
Junyu Lai71b51532024-02-01 10:39:01 +08003610 @CheckResult
3611 private boolean hasSystemBarServicePermission(int pid, int uid) {
3612 return hasAnyPermissionOf(mContext, pid, uid,
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003613 android.Manifest.permission.STATUS_BAR_SERVICE);
3614 }
3615
Junyu Lai71b51532024-02-01 10:39:01 +08003616 @CheckResult
3617 private boolean hasNetworkSignalStrengthWakeupPermission(int pid, int uid) {
3618 return hasAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003619 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003620 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3621 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003622 }
3623
Junyu Lai71b51532024-02-01 10:39:01 +08003624 @CheckResult
3625 private boolean hasConnectivityRestrictedNetworksPermission(int callingUid,
Paul Hu8fc2a552022-05-04 18:44:42 +08003626 boolean checkUidsAllowedList) {
Junyu Lai71b51532024-02-01 10:39:01 +08003627 if (hasAnyPermissionOf(mContext,
Paul Hu8fc2a552022-05-04 18:44:42 +08003628 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3629 return true;
3630 }
3631
3632 // fallback to ConnectivityInternalPermission
3633 // TODO: Remove this fallback check after all apps have declared
3634 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
Junyu Lai71b51532024-02-01 10:39:01 +08003635 if (hasAnyPermissionOf(mContext, android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003636 return true;
3637 }
3638
3639 // Check whether uid is in allowed on restricted networks list.
3640 if (checkUidsAllowedList
3641 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3642 return true;
3643 }
3644 return false;
3645 }
3646
3647 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3648 final int callingUid = mDeps.getCallingUid();
Junyu Lai71b51532024-02-01 10:39:01 +08003649 if (!hasConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003650 throw new SecurityException("ConnectivityService: user " + callingUid
3651 + " has no permission to access restricted network.");
3652 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003653 }
3654
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003655 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003656 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003657 }
3658
Junyu Lai71b51532024-02-01 10:39:01 +08003659 @CheckResult
3660 private boolean hasLocalMacAddressPermission(int pid, int uid) {
Roshan Pius98f59ec2021-02-23 08:47:39 -08003661 return PERMISSION_GRANTED == mContext.checkPermission(
3662 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3663 }
3664
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003665 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003666 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003667 }
3668
3669 private void sendInetConditionBroadcast(NetworkInfo info) {
3670 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3671 }
3672
Wink Saville4f0de1e2011-08-04 15:01:58 -07003673 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003674 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003675 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003676 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003677 if (info.isFailover()) {
3678 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3679 info.setFailover(false);
3680 }
3681 if (info.getReason() != null) {
3682 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3683 }
3684 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003685 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3686 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003687 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003688 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003689 return intent;
3690 }
3691
3692 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3693 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3694 }
3695
Michael Groover73f69482023-01-27 11:01:25 -06003696 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3697 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003698 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3699 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003700 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003701 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003702 if (!mSystemReady
3703 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003704 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003705 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003706 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003707 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003708 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003709 }
3710
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003711 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003712 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003713 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003714 final NetworkInfo ni = intent.getParcelableExtra(
3715 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003716 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3717 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003718 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003719 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003720 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003721 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003722 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003723 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003724 } finally {
3725 Binder.restoreCallingIdentity(ident);
3726 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003727 }
3728 }
3729
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003730 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3731 NetworkInfo info) {
3732 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003733 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003734
3735 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3736 try {
3737 // This allows us to discard older broadcasts still waiting to be delivered
3738 // which have the same namespace and key.
3739 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3740 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3741 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003742 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003743 } catch (UnsupportedApiLevelException e) {
3744 Log.wtf(TAG, "Using unsupported API" + e);
3745 }
3746 }
3747
3748 @VisibleForTesting
3749 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3750 final StringBuilder sb = new StringBuilder();
3751 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3752 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3753 sb.append(info.getExtraInfo());
3754 return sb.toString();
3755 }
3756
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003757 /**
Aaron Huang96011892020-06-27 07:18:23 +08003758 * Called by SystemServer through ConnectivityManager when the system is ready.
3759 */
3760 @Override
3761 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003762 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003763 throw new SecurityException("Calling Uid is not system uid.");
3764 }
3765 systemReadyInternal();
3766 }
3767
3768 /**
3769 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003770 */
3771 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003772 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003773 // Load flags after PackageManager is ready to query module version
3774 mFlags.loadFlags(mDeps, mContext);
3775
Aaron Huang9a57acf2020-12-08 10:03:29 +08003776 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3777 // listening network request which is sent by MultipathPolicyTracker won't be added
3778 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3779 // be called after PermissionMonitor#startMonitoring().
3780 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3781 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3782 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003783 final ConditionVariable startMonitoringDone = new ConditionVariable();
3784 mHandler.post(() -> {
3785 mPermissionMonitor.startMonitoring();
3786 startMonitoringDone.open();
3787 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003788 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003789 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003790
Hugo Benichie5220992017-04-26 14:53:28 +09003791 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003792 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003793 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003794 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003795 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003796 }
3797 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003798
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003799 // Create network requests for always-on networks.
3800 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003801
3802 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003803 // Note that updating can be skipped here if the list is empty only because no uid
3804 // rules are applied before system ready. Normally, the empty uid list means to clear
3805 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003806 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3807 updateMobileDataPreferredUids();
3808 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003809
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00003810 if (mSatelliteAccessController != null) {
3811 mSatelliteAccessController.start();
3812 }
3813
Motomu Utsumi166f9662022-09-01 10:35:29 +09003814 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003815 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003816 mBpfNetMaps.setPullAtomCallback(mContext);
3817 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003818 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3819 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003820 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3821 // have permission problem. While CV#block() is unbounded in time and can in principle block
3822 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3823 // could have blocked forever too.
3824 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003825 }
3826
The Android Open Source Project28527d22009-03-03 19:31:44 -08003827 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003828 * Start listening for default data network activity state changes.
3829 */
3830 @Override
3831 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003832 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003833 }
3834
3835 /**
3836 * Stop listening for default data network activity state changes.
3837 */
3838 @Override
3839 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003840 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003841 }
3842
3843 /**
3844 * Check whether the default network radio is currently active.
3845 */
3846 @Override
3847 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003848 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003849 }
3850
3851 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003852 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003853 * and set it on it's iface.
3854 */
Junyu Lai970963e2022-10-25 15:46:47 +08003855 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003856 final String iface = newLp.getInterfaceName();
3857 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003858 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003859 // Silently ignore unset MTU value.
3860 return;
3861 }
Hansen Kurli04252032022-12-07 11:21:49 +00003862 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3863 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3864 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003865 return;
3866 }
Hansen Kurli04252032022-12-07 11:21:49 +00003867 // Cannot set MTU without interface name
3868 if (TextUtils.isEmpty(iface)) {
3869 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003870 return;
3871 }
sy.yun4aa73922013-09-02 05:24:09 +09003872
Hansen Kurli04252032022-12-07 11:21:49 +00003873 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3874 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003875 return;
3876 }
3877
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003878 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003879 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003880 mNetd.interfaceSetMtu(iface, mtu);
3881 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003882 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003883 }
3884 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003885
Chenbo Feng15416292018-11-08 17:36:21 -08003886 @VisibleForTesting
3887 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003888
Junyu Lai970963e2022-10-25 15:46:47 +08003889 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003890 String[] values = null;
3891 if (tcpBufferSizes != null) {
3892 values = tcpBufferSizes.split(",");
3893 }
3894
3895 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003896 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003897 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3898 values = tcpBufferSizes.split(",");
3899 }
3900
3901 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3902
3903 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003904 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003905
Chenbo Feng15416292018-11-08 17:36:21 -08003906 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3907 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3908 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003909 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003910 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003911 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003912 }
3913 }
3914
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003915 @Override
3916 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003917 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003918 NETWORK_RESTORE_DELAY_PROP_NAME);
3919 if(restoreDefaultNetworkDelayStr != null &&
3920 restoreDefaultNetworkDelayStr.length() != 0) {
3921 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003922 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003923 } catch (NumberFormatException e) {
3924 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003925 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003926 // if the system property isn't set, use the value for the apn type
3927 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3928
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003929 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3930 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003931 }
3932 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003933 }
3934
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003935 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003936 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003937 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003938 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003939 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003940 // Start gathering diagnostic information.
3941 netDiags.add(new NetworkDiagnostics(
3942 nai.network,
3943 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003944 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003945 DIAG_TIME_MS));
3946 }
3947
3948 for (NetworkDiagnostics netDiag : netDiags) {
3949 pw.println();
3950 netDiag.waitForMeasurements();
3951 netDiag.dump(pw);
3952 }
3953 }
3954
The Android Open Source Project28527d22009-03-03 19:31:44 -08003955 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003956 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3957 @Nullable String[] args) {
Junyu Lai71b51532024-02-01 10:39:01 +08003958 if (!hasDumpPermission(mContext, TAG, writer)) return;
Chiachang Wanga101f852021-04-19 10:59:24 +08003959
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003960 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003961 }
3962
Junyu Lai71b51532024-02-01 10:39:01 +08003963 @CheckResult
3964 private boolean hasDumpPermission(Context context, String tag, PrintWriter pw) {
lucaslin99473f62020-12-10 15:10:54 +08003965 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3966 != PackageManager.PERMISSION_GRANTED) {
3967 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003968 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003969 + " due to missing android.permission.DUMP permission");
3970 return false;
3971 } else {
3972 return true;
3973 }
3974 }
3975
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003976 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003977 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003978
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003979 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003980 dumpNetworkDiagnostics(pw);
3981 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003982 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003983 dumpNetworks(pw);
3984 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003985 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003986 dumpNetworkRequests(pw);
3987 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003988 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3989 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3990 dumpTrafficController(pw, fd, verbose);
3991 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003992 }
Erik Kline9647f382015-06-05 17:47:34 +09003993
Junyu Lai0da479b2022-04-20 15:06:29 +08003994 pw.println("NetworkProviders for:");
3995 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003996 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003997 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003998 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003999 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004000 pw.println();
4001
Chalard Jean5b409c72021-02-04 13:12:59 +09004002 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004003 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09004004 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004005 pw.println("none");
4006 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09004007 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08004008 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08004009 pw.println();
4010
James Mattis8b298a02021-06-01 22:34:04 -07004011 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08004012 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07004013 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08004014 pw.decreaseIndent();
4015 pw.println();
4016
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004017 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004018 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004019 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004020 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004021 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08004022
junyulaif2c67e42018-08-07 19:50:45 +08004023 pw.println("Status for known UIDs:");
4024 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00004025 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08004026 for (int i = 0; i < size; i++) {
4027 // Don't crash if the array is modified while dumping in bugreports.
4028 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00004029 final int uid = mUidBlockedReasons.keyAt(i);
4030 final int blockedReasons = mUidBlockedReasons.valueAt(i);
4031 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00004032 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08004033 } catch (ArrayIndexOutOfBoundsException e) {
4034 pw.println(" ArrayIndexOutOfBoundsException");
4035 } catch (ConcurrentModificationException e) {
4036 pw.println(" ConcurrentModificationException");
4037 }
4038 }
4039 pw.println();
4040 pw.decreaseIndent();
4041
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004042 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004043 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004044 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004045 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004046 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004047
Junyu Lai0da479b2022-04-20 15:06:29 +08004048 pw.println("Network Offers:");
4049 pw.increaseIndent();
4050 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
4051 pw.println(offerInfo.offer);
4052 }
4053 pw.decreaseIndent();
4054 pw.println();
4055
Robert Greenwalt94e22142014-07-30 16:31:24 -07004056 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07004057
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004058 pw.println();
markchien5e866652019-09-30 14:40:57 +08004059 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07004060
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004061 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004062 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004063
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004064 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004065 dumpCloseFrozenAppSockets(pw);
4066
4067 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08004068 dumpBpfProgramStatus(pw);
4069
Chalard Jean53017782022-11-24 17:13:44 +09004070 if (null != mCarrierPrivilegeAuthenticator) {
4071 pw.println();
4072 mCarrierPrivilegeAuthenticator.dump(pw);
4073 }
4074
Junyu Lai155760b2023-10-05 14:51:00 +08004075 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004076
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004077 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004078 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09004079 pw.println("mNetworkRequestInfoLogs (most recent first):");
4080 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004081 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09004082 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09004083
4084 pw.println();
4085 pw.println("mNetworkInfoBlockingLogs (most recent first):");
4086 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004087 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09004088 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09004089
4090 pw.println();
4091 pw.println("NetTransition WakeLock activity (most recent first):");
4092 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004093 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
4094 pw.println("total releases: " + mTotalWakelockReleases);
4095 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
4096 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
4097 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4098 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4099 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4100 }
James Mattiscb1e0362021-04-06 17:07:42 -07004101 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004102
4103 pw.println();
4104 pw.println("bandwidth update requests (by uid):");
4105 pw.increaseIndent();
4106 synchronized (mBandwidthRequests) {
4107 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4108 pw.println("[" + mBandwidthRequests.keyAt(i)
4109 + "]: " + mBandwidthRequests.valueAt(i));
4110 }
4111 }
4112 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004113 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004114
James Mattiscb1e0362021-04-06 17:07:42 -07004115 pw.println();
4116 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4117 pw.increaseIndent();
4118 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004119 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004120 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004121
4122 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004123
4124 pw.println();
4125 pw.println("Permission Monitor:");
4126 pw.increaseIndent();
4127 mPermissionMonitor.dump(pw);
4128 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004129
4130 pw.println();
4131 pw.println("Legacy network activity:");
4132 pw.increaseIndent();
4133 mNetworkActivityTracker.dump(pw);
4134 pw.decreaseIndent();
Yang Sunca537d52024-01-19 12:53:50 +08004135
4136 pw.println();
4137 pw.println("Multicast routing supported: " +
4138 (mMulticastRoutingCoordinatorService != null));
The Android Open Source Project28527d22009-03-03 19:31:44 -08004139 }
4140
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004141 private void dumpNetworks(IndentingPrintWriter pw) {
4142 for (NetworkAgentInfo nai : networksSortedById()) {
4143 pw.println(nai.toString());
4144 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004145 pw.println("Nat464Xlat:");
4146 pw.increaseIndent();
4147 nai.dumpNat464Xlat(pw);
4148 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004149 pw.println(String.format(
4150 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4151 nai.numForegroundNetworkRequests(),
4152 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4153 nai.numBackgroundNetworkRequests(),
4154 nai.numNetworkRequests()));
4155 pw.increaseIndent();
4156 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4157 pw.println(nai.requestAt(i).toString());
4158 }
4159 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004160 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004161 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004162 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004163 pw.decreaseIndent();
4164 pw.decreaseIndent();
4165 }
4166 }
4167
James Mattis8b298a02021-06-01 22:34:04 -07004168 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4169 if (!mProfileNetworkPreferences.isEmpty()) {
4170 pw.println("Profile preferences:");
4171 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004172 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004173 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004174 }
James Mattis8b298a02021-06-01 22:34:04 -07004175 if (!mOemNetworkPreferences.isEmpty()) {
4176 pw.println("OEM preferences:");
4177 pw.increaseIndent();
4178 pw.println(mOemNetworkPreferences);
4179 pw.decreaseIndent();
4180 }
4181 if (!mMobileDataPreferredUids.isEmpty()) {
4182 pw.println("Mobile data preferred UIDs:");
4183 pw.increaseIndent();
4184 pw.println(mMobileDataPreferredUids);
4185 pw.decreaseIndent();
4186 }
James Mattis45d81842021-01-10 14:24:24 -08004187
James Mattis8b298a02021-06-01 22:34:04 -07004188 pw.println("Default requests:");
4189 pw.increaseIndent();
4190 dumpPerAppDefaultRequests(pw);
4191 pw.decreaseIndent();
4192 }
4193
4194 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004195 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4196 if (mDefaultRequest == defaultRequest) {
4197 continue;
4198 }
4199
James Mattis8b298a02021-06-01 22:34:04 -07004200 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4201 final String networkOutput;
4202 if (null == satisfier) {
4203 networkOutput = "null";
4204 } else if (mNoServiceNetwork.equals(satisfier)) {
4205 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004206 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004207 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004208 }
James Mattis8b298a02021-06-01 22:34:04 -07004209 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4210 ? "" : " asUid: " + defaultRequest.mAsUid;
4211 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4212 + defaultRequest.mPid + asUidString + "]";
4213 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4214 + " Preference order: " + defaultRequest.mPreferenceOrder
4215 + " Tracked UIDs: " + defaultRequest.getUids();
4216 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004217 }
4218 }
4219
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004220 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004221 NetworkRequestInfo[] infos = null;
4222 while (infos == null) {
4223 try {
4224 infos = requestsSortedById();
4225 } catch (ConcurrentModificationException e) {
4226 // mNetworkRequests should only be accessed from handler thread, except dump().
4227 // As dump() is never called in normal usage, it would be needlessly expensive
4228 // to lock the collection only for its benefit. Instead, retry getting the
4229 // requests if ConcurrentModificationException is thrown during dump().
4230 }
4231 }
4232 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004233 pw.println(nri.toString());
4234 }
4235 }
4236
Ken Chene6d511f2022-01-25 11:10:42 +08004237 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4238 boolean verbose) {
4239 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004240 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004241 } catch (ServiceSpecificException e) {
4242 pw.println(e.getMessage());
4243 } catch (IOException e) {
4244 loge("Dump BPF maps failed, " + e);
4245 }
4246 }
4247
Chalard Jean524f0b12021-10-25 21:11:56 +09004248 private void dumpAllRequestInfoLogsToLogcat() {
4249 try (PrintWriter logPw = new PrintWriter(new Writer() {
4250 @Override
4251 public void write(final char[] cbuf, final int off, final int len) {
4252 // This method is called with 0-length and 1-length arrays for empty strings
4253 // or strings containing only the DEL character.
4254 if (len <= 1) return;
4255 Log.e(TAG, new String(cbuf, off, len));
4256 }
4257 @Override public void flush() {}
4258 @Override public void close() {}
4259 })) {
4260 mNetworkRequestInfoLogs.dump(logPw);
4261 }
4262 }
4263
Hugo Benichia480ba52018-09-03 08:19:02 +09004264 /**
4265 * Return an array of all current NetworkAgentInfos sorted by network id.
4266 */
4267 private NetworkAgentInfo[] networksSortedById() {
4268 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004269 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004270 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004271 return networks;
4272 }
4273
4274 /**
4275 * Return an array of all current NetworkRequest sorted by request id.
4276 */
James Mattis258ea3c2020-11-15 15:04:40 -08004277 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004278 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004279 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004280 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004281 // Sort the array based off the NRI containing the min requestId in its requests.
4282 Arrays.sort(requests,
4283 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4284 Comparator.comparingInt(req -> req.requestId)).requestId
4285 )
4286 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004287 return requests;
4288 }
4289
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004290 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004291 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004292 if (officialNai != null && officialNai.equals(nai)) return true;
4293 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004294 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004295 " - " + nai);
4296 }
4297 return false;
4298 }
4299
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004300 private boolean isDisconnectRequest(Message msg) {
4301 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4302 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4303 return info.getState() == NetworkInfo.State.DISCONNECTED;
4304 }
4305
Robert Greenwalt2034b912009-08-12 16:08:25 -07004306 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004307 private class NetworkStateTrackerHandler extends Handler {
4308 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004309 super(looper);
4310 }
4311
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004312 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004313 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4314 final NetworkAgentInfo nai = arg.first;
4315 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004316 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004317 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004318 }
4319 return;
4320 }
4321
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004322 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004323 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004324 return;
4325 }
4326
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004327 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004328 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004329 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4330 if (!nai.respectsNcStructuralConstraints(proposed)) {
4331 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4332 + nai.networkCapabilities + " -> " + proposed);
4333 disconnectAndDestroyNetwork(nai);
4334 return;
4335 }
4336 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004337 final NetworkCapabilities sanitized =
4338 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004339 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004340 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004341 break;
4342 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004343 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004344 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004345 processLinkPropertiesFromAgent(nai, newLp);
4346 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004347 break;
4348 }
4349 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004350 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004351 updateNetworkInfo(nai, info);
4352 break;
4353 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004354 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4355 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004356 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004357 break;
4358 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004359 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004360 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004361 break;
4362 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004363 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004364 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004365 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004366 // Note that if the NAI had been connected, this would affect the
4367 // score, and therefore would require re-mixing the score and performing
4368 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004369 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004370 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4371 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004372 // Mark the network as temporarily accepting partial connectivity so that it
4373 // will be validated (and possibly become default) even if it only provides
4374 // partial internet access. Note that if user connects to partial connectivity
4375 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4376 // out of wifi coverage) and if the same wifi is available again, the device
4377 // will auto connect to this wifi even though the wifi has "no internet".
4378 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004379 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004380 break;
4381 }
junyulai011b1f12019-01-03 18:50:15 +08004382 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004383 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004384 break;
4385 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004386 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004387 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004388 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004389
4390 if (isLegacyLockdownNai(nai)
4391 && (underlying == null || underlying.size() != 1)) {
4392 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4393 + " must have exactly one underlying network: " + underlying);
4394 }
4395
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004396 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4397 nai.declaredUnderlyingNetworks = (underlying != null)
4398 ? underlying.toArray(new Network[0]) : null;
4399
4400 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4401 if (DBG) {
4402 log(nai.toShortString() + " changed underlying networks to "
4403 + Arrays.toString(nai.declaredUnderlyingNetworks));
4404 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004405 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004406 notifyIfacesChangedForNetworkStats();
4407 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004408 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004409 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004410 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4411 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4412 nai.teardownDelayMs = msg.arg1;
4413 } else {
4414 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4415 }
Chalard Jean550b5212021-03-05 23:07:53 +09004416 break;
4417 }
4418 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4419 nai.setLingerDuration((int) arg.second);
4420 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004421 }
Tyler Wear72388212021-09-09 14:49:02 -07004422 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4423 DscpPolicy policy = (DscpPolicy) arg.second;
4424 if (mDscpPolicyTracker != null) {
4425 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4426 }
4427 break;
4428 }
4429 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4430 if (mDscpPolicyTracker != null) {
4431 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4432 }
4433 break;
4434 }
4435 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4436 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004437 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004438 }
4439 break;
4440 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004441 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004442 if (!nai.everConnected()) {
4443 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4444 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004445 teardownUnneededNetwork(nai);
4446 break;
4447 }
4448
4449 if (nai.isDestroyed()) {
4450 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4451 + ", ignoring");
4452 break;
4453 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004454
4455 final int timeoutMs = (int) arg.second;
4456 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4457 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4458 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4459 }
4460
4461 // Marking a network awaiting replacement is used to ensure that any requests
4462 // satisfied by the network do not switch to another network until a
4463 // replacement is available or the wait for a replacement times out.
4464 // If the network is inactive (i.e., nascent or lingering), then there are no
4465 // such requests, and there is no point keeping it. Just tear it down.
4466 // Note that setLingerDuration(0) cannot be used to do this because the network
4467 // could be nascent.
4468 nai.clearInactivityState();
4469 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4470 Log.d(TAG, nai.toShortString()
4471 + " marked awaiting replacement is unneeded, tearing down instead");
4472 teardownUnneededNetwork(nai);
4473 break;
4474 }
4475
4476 Log.d(TAG, "Marking " + nai.toShortString()
4477 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4478 destroyNativeNetwork(nai);
4479
4480 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4481 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4482 // consider the fact that the network could already have disconnected or been
4483 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4484 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4485 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4486 mKeepaliveTracker.handleStopAllKeepalives(nai,
4487 SocketKeepalive.ERROR_INVALID_NETWORK);
4488
4489 nai.updateScoreForNetworkAgentUpdate();
4490 // This rematch is almost certainly not going to result in any changes, because
4491 // the destroyed flag is only just above the "current satisfier wins"
4492 // tie-breaker. But technically anything that affects scoring should rematch.
4493 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004494 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004495 break;
4496 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004497 }
4498 }
4499
4500 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004501 final int netId = msg.arg2;
4502 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004503 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004504 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004505 switch (msg.what) {
4506 default:
4507 return false;
lucasline117e2e2019-10-22 18:27:33 +08004508 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004509 if (nai == null) {
4510 break;
4511 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004512 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4513 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004514 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004515 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004516 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004517 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004518 if (probePrivateDnsCompleted) {
4519 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4520 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004521 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004522 }
4523 // Only show the notification when the private DNS is broken and the
4524 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004525 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004526 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4527 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004528 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004529 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4530 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4531 // private DNS is broken, it means this network is being reevaluated.
4532 // Either probing private DNS is not necessary any more or it hasn't been
4533 // done yet. In either case, the networkCapabilities should be updated to
4534 // reflect the new status.
4535 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004536 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004537 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004538 }
4539 break;
4540 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004541 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004542 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4543
Erik Kline31b4a9e2018-01-11 21:07:29 +09004544 if (nai == null) break;
4545
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004546 handleNetworkTested(nai, results.mTestResult,
4547 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004548 break;
4549 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004550 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004551 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004552 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004553 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004554 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004555 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004556 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4557 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004558 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004559 if (nai == null) {
4560 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4561 break;
4562 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004563 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004564 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004565 (PendingIntent) msg.obj,
4566 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004567 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004568 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004569 break;
4570 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004571 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004572 if (nai == null) break;
4573
Erik Kline9a62f012018-03-21 07:18:33 -07004574 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004575 break;
4576 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004577 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004578 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004579 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004580 break;
4581 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004582 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004583 return true;
4584 }
4585
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004586 private void handleNetworkTested(
4587 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004588 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4589 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004590 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004591
4592 // If there is any kind of working networking, then the NAI has been evaluated
4593 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4594 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004595 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004596 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004597 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4598 // any callback that receives onAvailable for that rematch receives an extra caps
4599 // callback. To prevent that, update the score in the agent so the updates below won't
4600 // see an update to both caps and score at the same time.
4601 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004602 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4603
he_won.hwang881307a2022-03-15 21:23:52 +09004604 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4605 // Assume the validation failure is due to a temporary failure after roaming
4606 // and ignore it. NetworkMonitor will continue to retry validation. If it
4607 // continues to fail after the block timeout expires, the network will be
4608 // marked unvalidated. If it succeeds, then validation state will not change.
4609 return;
4610 }
4611
Chalard Jean254bd162022-08-25 13:04:51 +09004612 final boolean wasValidated = nai.isValidated();
4613 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004614 final boolean wasPortal = nai.captivePortalDetected();
4615 nai.setPartialConnectivity(partial);
4616 nai.setCaptivePortalDetected(portal);
4617 nai.updateScoreForNetworkAgentUpdate();
4618 final boolean partialConnectivityChanged = (wasPartial != partial);
4619 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004620
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004621 if (DBG) {
4622 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4623 ? " with redirect to " + redirectUrl
4624 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004625 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004626 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004627 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004628 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004629 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004630 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004631 if (valid) {
4632 handleFreshlyValidatedNetwork(nai);
4633 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4634 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004635 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004636 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004637 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004638 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004639 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004640 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004641 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004642 NotificationType.PRIVATE_DNS_BROKEN);
4643 // If network becomes valid, the hasShownBroken should be reset for
4644 // that network so that the notification will be fired when the private
4645 // DNS is broken again.
4646 nai.networkAgentConfig.hasShownBroken = false;
4647 }
4648 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004649 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004650 } else if (portalChanged) {
4651 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004652 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004653 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4654 nai.onPreventAutomaticReconnect();
4655 teardownUnneededNetwork(nai);
4656 return;
4657 } else {
4658 updateCapabilitiesForNetwork(nai);
4659 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004660 } else if (becameEvaluated) {
4661 // If valid or partial connectivity changed, updateCapabilities* has
4662 // done the rematch.
4663 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004664 }
4665 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004666
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004667 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004668 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004669 nai.onValidationStatusChanged(
4670 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4671 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004672
4673 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004674 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004675 // immediately. Re-notify partial connectivity silently if no internet
4676 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004677 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004678 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004679 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4680 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004681 }
4682
Chalard Jean254bd162022-08-25 13:04:51 +09004683 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004684 handleNetworkUnvalidated(nai);
4685 }
4686 }
4687
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004688 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4689 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4690 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4691 // Do not avoid captive portal when network is wear proxy.
4692 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4693 }
4694
Calvin Ondada1452016-10-11 15:10:46 -07004695 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004696 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4697 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004698 }
4699
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004700 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4701 switch (msg.what) {
4702 default:
4703 return false;
4704 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4705 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4706 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4707 handleLingerComplete(nai);
4708 }
4709 break;
4710 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004711 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4712 handleNetworkAgentRegistered(msg);
4713 break;
4714 }
4715 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4716 handleNetworkAgentDisconnected(msg);
4717 break;
4718 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004719 }
4720 return true;
4721 }
4722
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004723 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004724 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004725 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004726 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004727 maybeHandleNetworkAgentMessage(msg);
4728 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004729 }
4730 }
4731
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004732 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004733 private final int mNetId;
4734 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004735
4736 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004737 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004738 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004739 }
4740
4741 @Override
4742 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4743 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004744 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004745 }
4746
4747 @Override
4748 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004749 // Legacy version of notifyNetworkTestedWithExtras.
4750 // Would only be called if the system has a NetworkStack module older than the
4751 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004752 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004753 }
4754
4755 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004756 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004757 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4758 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004759 final Message msg = mTrackerHandler.obtainMessage(
4760 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004761 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004762 new NetworkTestedResults(
4763 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004764 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004765
4766 // Invoke ConnectivityReport generation for this Network test event.
4767 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4768 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004769
Cody Kestingf1120be2020-08-03 18:01:40 -07004770 // NetworkMonitor reports the network validation result as a bitmask while
4771 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4772 // logical value for ConnectivityDiagnostics.
4773 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4774 p.result);
4775
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004776 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004777 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004778 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4779 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4780
Aaron Huang959d3642021-01-21 15:47:41 +08004781 ConnectivityReportEvent reportEvent =
4782 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4783 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004784 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004785 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004786 }
4787
4788 @Override
4789 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4790 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4791 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004792 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004793 }
4794
4795 @Override
lucasline117e2e2019-10-22 18:27:33 +08004796 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4797 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4798 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004799 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004800 }
4801
4802 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004803 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4804 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4805 EVENT_CAPPORT_DATA_CHANGED,
4806 0, mNetId, data));
4807 }
4808
4809 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004810 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004811 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004812 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004813
4814 final PendingIntent pendingIntent;
4815 // Only the system server can register notifications with package "android"
4816 final long token = Binder.clearCallingIdentity();
4817 try {
paulhu7746e4e2020-06-09 19:07:03 +08004818 pendingIntent = PendingIntent.getBroadcast(
4819 mContext,
4820 0 /* requestCode */,
4821 intent,
4822 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004823 } finally {
4824 Binder.restoreCallingIdentity(token);
4825 }
4826 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4827 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004828 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004829 }
4830
4831 @Override
4832 public void hideProvisioningNotification() {
4833 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004834 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004835 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004836
4837 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004838 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004839 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004840 }
4841
4842 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004843 public int getInterfaceVersion() {
4844 return this.VERSION;
4845 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004846
4847 @Override
4848 public String getInterfaceHash() {
4849 return this.HASH;
4850 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004851 }
4852
Cody Kestingf1120be2020-08-03 18:01:40 -07004853 /**
4854 * Converts the given NetworkMonitor-specific validation result bitmask to a
4855 * ConnectivityDiagnostics-specific validation result int.
4856 */
4857 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4858 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4859 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4860 }
4861 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4862 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4863 }
4864 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4865 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4866 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4867 }
4868
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004869 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004870 log("Data stall detected with methods: " + p.detectionMethod);
4871
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004872 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004873 int detectionMethod = 0;
4874 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4875 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4876 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4877 }
4878 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4879 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4880 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4881 p.tcpMetricsCollectionPeriodMillis);
4882 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004883 }
4884
Cody Kestingf53a0752020-04-15 12:33:28 -07004885 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004886 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004887 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004888
4889 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4890 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4891 // the cost of going through two handlers.
4892 mConnectivityDiagnosticsHandler.sendMessage(msg);
4893 }
4894
Cody Kestingb37958e2020-05-15 10:36:01 -07004895 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4896 return (p.detectionMethod & detectionMethod) != 0;
4897 }
4898
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004899 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4900 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004901 }
4902
Erik Klinea73af002018-06-26 18:53:43 +09004903 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4904 if (nai == null) return;
4905 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4906 // in order to restart a validation pass from within netd.
4907 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00004908 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004909 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004910 }
4911 }
4912
Erik Kline31b4a9e2018-01-11 21:07:29 +09004913 private void handlePrivateDnsSettingsChanged() {
4914 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4915
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004916 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004917 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004918 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004919 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4920 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004921 }
4922 }
4923
Erik Kline9a62f012018-03-21 07:18:33 -07004924 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4925 // Private DNS only ever applies to networks that might provide
4926 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004927 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004928
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004929 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004930 // schedule DNS resolutions. If a DNS resolution is required the
4931 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004932 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004933
4934 // With Private DNS bypass support, we can proceed to update the
4935 // Private DNS config immediately, even if we're in strict mode
4936 // and have not yet resolved the provider name into a set of IPs.
4937 updatePrivateDns(nai, cfg);
4938 }
4939
4940 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4941 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004942 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004943 }
4944
dalyk1720e542018-03-05 12:42:22 -05004945 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4946 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4947 if (nai == null) {
4948 return;
4949 }
4950 mDnsManager.updatePrivateDnsValidation(update);
4951 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4952 }
4953
paulhu7c0a2e62021-01-08 00:51:49 +08004954 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004955 int prefixLength) {
4956 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4957 if (nai == null) return;
4958
paulhu7c0a2e62021-01-08 00:51:49 +08004959 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4960 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004961
4962 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004963 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004964 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004965 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004966 prefixLength);
4967 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004968 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004969 return;
4970 }
4971 }
4972
Lorenzo Colittid523d142020-04-01 20:16:30 +09004973 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004974 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4975 }
4976
Hai Shalome58bdc62021-01-11 18:45:34 -08004977 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004978 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004979 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004980 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4981 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4982 }
4983
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004984 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004985 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004986 * @param nai the agent info to update
4987 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004988 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004989 */
junyulai2b6f0c22021-02-03 20:15:30 +08004990 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4991 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4992 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004993 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004994 // one lingered request, set inactive.
4995 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004996 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004997 if (DBG) log("Unsetting inactive " + nai.toShortString());
4998 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004999 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08005000 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005001 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08005002 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
5003 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005004 }
junyulai2b6f0c22021-02-03 20:15:30 +08005005 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005006 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005007 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005008 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005009 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05005010 }
5011
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005012 private void handleNetworkAgentRegistered(Message msg) {
5013 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
5014 if (!mNetworkAgentInfos.contains(nai)) {
5015 return;
5016 }
5017
5018 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
5019 if (VDBG) log("NetworkAgent registered");
5020 } else {
5021 loge("Error connecting NetworkAgent");
5022 mNetworkAgentInfos.remove(nai);
5023 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005024 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005025 synchronized (mNetworkForNetId) {
5026 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005027 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005028 mNetIdManager.releaseNetId(nai.network.getNetId());
5029 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09005030 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005031 }
5032 }
5033 }
Paul Jensend5f53392014-11-25 15:26:53 -05005034
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005035 @VisibleForTesting
5036 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09005037 // The feature of creating the networks immediately was slated for U, but race conditions
5038 // detected late required this was flagged off.
5039 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
5040 // in NetworkAgentTest.
5041 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005042 }
5043
5044 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
5045 @NonNull NetworkInfo.State state) {
5046 if (nai.isCreated()) return false;
5047 if (state == NetworkInfo.State.CONNECTED) return true;
5048 if (state != NetworkInfo.State.CONNECTING) {
5049 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09005050 if (shouldCreateNetworksImmediately()) {
5051 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
5052 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005053 return false;
5054 }
5055 return nai.isVPN() || shouldCreateNetworksImmediately();
5056 }
5057
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005058 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09005059 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005060 }
5061
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005062 @VisibleForTesting
5063 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09005064 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09005065 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005066
5067 // If the network never roamed, return false. The check below is not sufficient if time
5068 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
5069 if (nai.lastRoamTime == 0) return false;
5070
he_won.hwang881307a2022-03-15 21:23:52 +09005071 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
5072 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005073 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09005074 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09005075 final long currentTimeMs = SystemClock.elapsedRealtime();
5076 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09005077 if (timeSinceLastRoam <= blockTimeOut) {
5078 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
5079 return true;
5080 }
5081 }
5082 return false;
5083 }
5084
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005085 private void handleNetworkAgentDisconnected(Message msg) {
5086 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07005087 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005088 }
5089
Chalard Jeand9fffc32018-05-11 20:19:20 +09005090 // Destroys a network, remove references to it from the internal state managed by
5091 // ConnectivityService, free its interfaces and clean up.
5092 // Must be called on the Handler thread.
5093 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005094 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07005095
5096 if (!mNetworkAgentInfos.contains(nai)) return;
5097
Chalard Jeand9fffc32018-05-11 20:19:20 +09005098 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09005099 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005100 }
lucaslinb25c9a62019-02-12 15:30:13 +08005101 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005102 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005103 // A network agent has disconnected.
5104 // TODO - if we move the logic to the network agent (have them disconnect
5105 // because they lost all their requests or because their score isn't good)
5106 // then they would disconnect organically, report their new state and then
5107 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08005108 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005109 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5110 null, null);
5111 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005112 final boolean wasDefault = isDefaultNetwork(nai);
5113 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005114 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005115 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005116 if (mTrackMultiNetworkActivities) {
5117 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5118 // the network becomes no longer the default network.
5119 mNetworkActivityTracker.removeDataActivityTracking(nai);
5120 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005121 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005122 // If this was a local network forwarded to some upstream, or if some local network was
5123 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005124 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005125 // If this is a local network with an upstream selector, remove the associated network
5126 // request.
5127 if (nai.isLocalNetwork()) {
5128 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5129 if (null != selector) {
5130 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5131 }
5132 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005133 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5134 // by other networks that are already connected. Perhaps that can be done by
5135 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5136 // of rematchAllNetworksAndRequests
5137 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005138 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005139
5140 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005141 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5142 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005143 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005144 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005145 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005146 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005147 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005148 synchronized (mNetworkForNetId) {
5149 // Remove the NetworkAgent, but don't mark the netId as
5150 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005151 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005152 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005153 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005154 // Update allowed network lists in netd. This should be called after removing nai
5155 // from mNetworkAgentInfos.
5156 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005157 // Remove all previously satisfied requests.
5158 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005159 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005160 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005161 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005162 if (currentNetwork != null
5163 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005164 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005165 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5166 // rematch not to keep disconnected agents instead of setting it here ; this
5167 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005168 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005169 for (final NetworkOfferInfo noi : mNetworkOffers) {
5170 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005171 }
James Mattise3ef1912020-12-20 11:09:58 -08005172
Chalard Jean5b409c72021-02-04 13:12:59 +09005173 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005174 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005175 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005176 ensureNetworkTransitionWakelock(nai.toShortString());
5177 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005178 }
5179 }
junyulai2b6f0c22021-02-03 20:15:30 +08005180 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005181 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005182 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005183 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005184 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005185 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005186 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005187
Aaron Huang9fe47be2021-06-08 13:11:45 +08005188 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5189 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5190 // not called by the rematch in this case. This is because the code above unset
5191 // this network from the default request's satisfier, and that is what the rematch
5192 // is using as its source data to know what the old satisfier was. So as far as the
5193 // rematch above is concerned, the old default network was null.
5194 // Therefore if there is no new default, the default network was null and is still
5195 // null, thus there was no change so makeDefault() is not called. So if the old
5196 // network had a proxy and there is no new default, the proxy tracker should be told
5197 // that there is no longer a default proxy.
5198 // Strictly speaking this is not essential because having a proxy setting when
5199 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5200 mProxyTracker.setDefaultProxy(null);
5201 }
5202
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005203 // Immediate teardown.
5204 if (nai.teardownDelayMs == 0) {
5205 destroyNetwork(nai);
5206 return;
5207 }
5208
5209 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005210 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305211 try {
5212 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5213 } catch (RemoteException e) {
5214 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5215 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005216 }
5217 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5218 }
5219
5220 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005221 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005222 // Tell netd to clean up the configuration for this network
5223 // (routing rules, DNS, etc).
5224 // This may be slow as it requires a lot of netd shelling out to ip and
5225 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005226 // after we've rematched networks with requests (which might change the default
5227 // network or service a new request from an app), so network traffic isn't interrupted
5228 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005229 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005230 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005231 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005232 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5233 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5234 // false if the network was never created.
5235 // TODO: delete when S is no longer supported.
5236 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005237 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005238 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005239 }
5240
Chalard Jean1e4c2182023-10-06 18:45:53 +09005241 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005242 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005243 // Step 1 : maybe this network was the upstream for one or more local networks.
5244 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5245 if (!local.isLocalNetwork()) continue;
5246 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5247 if (null == selector) continue;
5248 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5249 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5250 // called after removing all associated NRIs from mNetworkRequests.
5251 if (null == nri) continue;
5252 final NetworkAgentInfo satisfier = nri.getSatisfier();
5253 if (disconnecting != satisfier) continue;
5254 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005255 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5256 // correctly contains null as an upstream.
5257 if (sendCallbacks) {
5258 nri.setSatisfier(null, null);
5259 notifyNetworkCallbacks(local,
5260 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5261 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005262 }
5263
5264 // Step 2 : maybe this is a local network that had an upstream.
5265 if (!disconnecting.isLocalNetwork()) return;
5266 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5267 if (null == selector) return;
5268 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5269 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5270 // is called after removing all associated NRIs from mNetworkRequests.
5271 if (null == nri) return;
5272 final NetworkAgentInfo satisfier = nri.getSatisfier();
5273 if (null == satisfier) return;
5274 removeLocalNetworkUpstream(disconnecting, satisfier);
5275 }
5276
5277 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5278 @NonNull final NetworkAgentInfo upstream) {
5279 try {
Yang Sun29037f62023-12-04 10:31:58 +08005280 final String localNetworkInterfaceName = localAgent.linkProperties.getInterfaceName();
5281 final String upstreamNetworkInterfaceName = upstream.linkProperties.getInterfaceName();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005282 mRoutingCoordinatorService.removeInterfaceForward(
Yang Sun29037f62023-12-04 10:31:58 +08005283 localNetworkInterfaceName,
5284 upstreamNetworkInterfaceName);
5285 disableMulticastRouting(localNetworkInterfaceName, upstreamNetworkInterfaceName);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005286 } catch (RemoteException e) {
5287 loge("Couldn't remove interface forward for "
5288 + localAgent.linkProperties.getInterfaceName() + " to "
5289 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5290 }
5291 }
5292
Ken Chen6df7a902021-04-09 15:08:42 +08005293 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005294 try {
5295 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005296 final NativeNetworkConfig config;
5297 if (nai.isVPN()) {
5298 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005299 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005300 return false;
5301 }
5302 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5303 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005304 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005305 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005306 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005307 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005308 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5309 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005310 getNetworkPermission(nai.networkCapabilities),
5311 false /* secure */,
5312 VpnManager.TYPE_VPN_NONE,
5313 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005314 }
Ken Chen6df7a902021-04-09 15:08:42 +08005315 mNetd.networkCreate(config);
5316 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005317 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5318 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005319 return true;
5320 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005321 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005322 return false;
5323 }
5324 }
5325
Ken Chen6df7a902021-04-09 15:08:42 +08005326 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005327 if (mDscpPolicyTracker != null) {
5328 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5329 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005330 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005331 // the interface is going to go away. Don't send the callbacks however ; if the network
5332 // was is being disconnected the callbacks have already been sent, and if it is being
5333 // destroyed pending replacement they will be sent when it is disconnected.
5334 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005335 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005336 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005337 } catch (RemoteException | ServiceSpecificException e) {
5338 loge("Exception destroying network(networkDestroy): " + e);
5339 }
5340 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005341 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005342 } catch (RemoteException | ServiceSpecificException e) {
5343 loge("Exception destroying network: " + e);
5344 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005345 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5346 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5347 // gets created, could add data to DnsManager data structures that will never get deleted.
5348 mDnsManager.removeNetwork(nai.network);
5349
5350 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005351 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005352 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5353 }
5354
Chalard Jean254bd162022-08-25 13:04:51 +09005355 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005356 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005357 }
5358
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005359 // If this method proves to be too slow then we can maintain a separate
5360 // pendingIntent => NetworkRequestInfo map.
5361 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5362 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005363 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5364 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5365 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005366 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005367 return entry.getValue();
5368 }
5369 }
5370 return null;
5371 }
5372
Chalard Jean524f0b12021-10-25 21:11:56 +09005373 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005374 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005375 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5376 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5377 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5378 // bug is fixed.
5379 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005380 throw new IllegalStateException("This NRI is already registered. New : " + nri
5381 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005382 }
5383 }
5384 }
5385 }
5386
Chalard Jeanac9ace02022-01-26 16:54:05 +09005387 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5388 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005389 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005390 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005391 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005392 }
5393 return false;
5394 }
5395
Ying Xu0d06b942024-02-09 21:04:08 -08005396 private int getSubscriptionIdFromNetworkCaps(@NonNull final NetworkCapabilities caps) {
5397 if (mCarrierPrivilegeAuthenticator != null) {
5398 return mCarrierPrivilegeAuthenticator.getSubIdFromNetworkCapabilities(caps);
5399 }
5400 return SubscriptionManager.INVALID_SUBSCRIPTION_ID;
5401 }
5402
James Mattisf7027322020-12-13 16:28:14 -08005403 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005404 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005405 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5406 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5407 final NetworkRequestInfo existingRequest =
5408 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005409 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005410 if (DBG) {
5411 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5412 + nri.mRequests.get(0) + " because their intents matched.");
5413 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005414 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005415 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005416 }
Erik Kline05f2b402015-04-30 12:58:40 +09005417 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005418 }
5419
James Mattisf7027322020-12-13 16:28:14 -08005420 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005421 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005422 }
5423
James Mattis3ce3d3c2021-02-09 18:18:28 -08005424 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005425 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005426 for (final NetworkRequestInfo nri : nris) {
5427 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005428 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005429 for (final NetworkRequest req : nri.mRequests) {
5430 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005431 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005432 if (req.isListen()) {
5433 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5434 if (req.networkCapabilities.hasSignalStrength()
5435 && network.satisfiesImmutableCapabilitiesOf(req)) {
5436 updateSignalStrengthThresholds(network, "REGISTER", req);
5437 }
James Mattisf7027322020-12-13 16:28:14 -08005438 }
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005439 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5440 mNetworkRequestStateStatsMetrics.onNetworkRequestReceived(req);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005441 }
5442 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005443
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005444 // If this NRI has a satisfier already, it is replacing an older request that
5445 // has been removed. Track it.
5446 final NetworkRequest activeRequest = nri.getActiveRequest();
5447 if (null != activeRequest) {
5448 // If there is an active request, then for sure there is a satisfier.
5449 nri.getSatisfier().addRequest(activeRequest);
5450 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005451 }
James Mattisf7027322020-12-13 16:28:14 -08005452
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005453 if (mFlags.noRematchAllRequestsOnRegister()) {
5454 rematchNetworksAndRequests(nris);
5455 } else {
5456 rematchAllNetworksAndRequests();
5457 }
James Mattis45d81842021-01-10 14:24:24 -08005458
Chalard Jean0354d8c2021-01-12 10:58:56 +09005459 // Requests that have not been matched to a network will not have been sent to the
5460 // providers, because the old satisfier and the new satisfier are the same (null in this
5461 // case). Send these requests to the providers.
5462 for (final NetworkRequestInfo nri : nris) {
5463 for (final NetworkOfferInfo noi : mNetworkOffers) {
5464 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005465 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005466 }
5467 }
5468
James Mattisf7027322020-12-13 16:28:14 -08005469 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5470 final int callingUid) {
5471 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005472 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005473 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5474 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5475 handleReleaseNetworkRequest(
5476 nri.mRequests.get(0),
5477 callingUid,
5478 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005479 }
5480 }
5481
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005482 // Determines whether the network is the best (or could become the best, if it validated), for
5483 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5484 // on the value of reason:
5485 //
5486 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5487 // then it should be torn down.
5488 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5489 // then it should be lingered.
5490 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005491 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005492
Chalard Jean254bd162022-08-25 13:04:51 +09005493 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005494 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5495 return false;
5496 }
5497
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005498 final int numRequests;
5499 switch (reason) {
5500 case TEARDOWN:
5501 numRequests = nai.numRequestNetworkRequests();
5502 break;
5503 case LINGER:
5504 numRequests = nai.numForegroundNetworkRequests();
5505 break;
5506 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005507 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005508 return true;
5509 }
5510
Chalard Jean947acd42021-03-08 22:29:27 +09005511 if (numRequests > 0) return false;
5512
Paul Jensende49eb12015-06-25 15:30:08 -04005513 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005514 if (reason == UnneededFor.LINGER
5515 && !nri.isMultilayerRequest()
5516 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005517 // Background requests don't affect lingering.
5518 continue;
5519 }
5520
James Mattis3d229892020-11-16 16:46:28 -08005521 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005522 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005523 }
5524 }
Paul Jensende49eb12015-06-25 15:30:08 -04005525 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005526 }
5527
James Mattis3d229892020-11-16 16:46:28 -08005528 private boolean isNetworkPotentialSatisfier(
5529 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005530 // While destroyed network sometimes satisfy requests (including occasionally newly
5531 // satisfying requests), *potential* satisfiers are networks that might beat a current
5532 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5533 // because it's never a good idea to keep a destroyed network in case it validates.
5534 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5535 // candidate after it's been replaced by another unvalidated network.
5536 if (candidate.isDestroyed()) return false;
5537 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005538 // request, return immediately. For multilayer requests, check to see if any of the
5539 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005540 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5541 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005542 return false;
5543 }
5544 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005545 // This multilayer listen request is satisfied therefore no further requests need to be
5546 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005547 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005548 return false;
5549 }
James Mattis3d229892020-11-16 16:46:28 -08005550 // As non-multilayer listen requests have already returned, the below would only happen
5551 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005552 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005553 continue;
5554 }
Chalard Jean80685f42023-10-30 18:31:27 +09005555 // If there is hope for this network might validate and subsequently become the best
5556 // network for that request, then it is needed. Note that this network can't already
5557 // be the best for this request, or it would be the current satisfier, and therefore
5558 // there would be no need to call this method to find out if it is a *potential*
5559 // satisfier ("unneeded", the only caller, only calls this if this network currently
5560 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005561 if (candidate.satisfies(req)) {
5562 // As soon as a network is found that satisfies a request, return. Specifically for
5563 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5564 // is important so as to not evaluate lower priority requests further in
5565 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005566 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5567 ? nri.getSatisfier() : null;
5568 // Note that this catches two important cases:
5569 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5570 // is currently satisfying the request. This is desirable when
5571 // cellular ends up validating but WiFi does not.
5572 // 2. Unvalidated WiFi will not be reaped when validated cellular
5573 // is currently satisfying the request. This is desirable when
5574 // WiFi ends up validating and out scoring cellular.
5575 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005576 }
5577 }
5578
5579 return false;
5580 }
5581
Erik Kline0c04b742016-07-07 16:50:58 +09005582 private NetworkRequestInfo getNriForAppRequest(
5583 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005584 // Looking up the app passed param request in mRequests isn't possible since it may return
5585 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5586 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005587 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5588 // to avoid potential race conditions when validating a package->uid mapping when sending
5589 // the callback on the very low-chance that an application shuts down prior to the callback
5590 // being sent.
5591 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5592 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005593
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005594 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005595 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005596 log(String.format("UID %d attempted to %s for unowned request %s",
5597 callingUid, requestedOperation, nri));
5598 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005599 }
Erik Kline0c04b742016-07-07 16:50:58 +09005600 }
5601
5602 return nri;
5603 }
5604
James Mattisf7027322020-12-13 16:28:14 -08005605 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5606 final String callingMethod) {
5607 if (nri.isMultilayerRequest()) {
5608 throw new IllegalStateException(
5609 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005610 }
5611 }
5612
James Mattisf7027322020-12-13 16:28:14 -08005613 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005614 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005615 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5616 // single NetworkRequest and thus does not apply to multilayer requests.
5617 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5618 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005619 return;
5620 }
James Mattis2516da32021-01-31 17:06:19 -08005621 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005622 return;
5623 }
James Mattisf7027322020-12-13 16:28:14 -08005624 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5625 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005626 }
5627 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005628 callCallbackForRequest(
5629 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005630 }
5631
James Mattisf7027322020-12-13 16:28:14 -08005632 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5633 final int callingUid,
5634 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005635 final NetworkRequestInfo nri =
5636 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5637 if (nri == null) {
5638 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005639 }
James Mattisf7027322020-12-13 16:28:14 -08005640 if (VDBG || (DBG && request.isRequest())) {
5641 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005642 }
5643 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005644 if (callOnUnavailable) {
5645 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5646 }
Erik Kline155a59a2015-11-25 12:49:38 +09005647 }
Erik Kline0c04b742016-07-07 16:50:58 +09005648
James Mattisa076c532020-12-02 14:12:41 -08005649 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005650 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005651 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005652 if (null == mNetworkRequests.remove(req)) {
5653 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5654 continue;
5655 }
James Mattisa076c532020-12-02 14:12:41 -08005656 if (req.isListen()) {
5657 removeListenRequestFromNetworks(req);
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005658 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5659 mNetworkRequestStateStatsMetrics.onNetworkRequestRemoved(req);
James Mattisa076c532020-12-02 14:12:41 -08005660 }
5661 }
James Mattis8f036802021-06-20 16:26:01 -07005662 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005663 if (mDefaultNetworkRequests.remove(nri)) {
5664 // If this request was one of the defaults, then the UID rules need to be updated
5665 // WARNING : if the app(s) for which this network request is the default are doing
5666 // traffic, this will kill their connected sockets, even if an equivalent request
5667 // is going to be reinstated right away ; unconnected traffic will go on the default
5668 // until the new default is set, which will happen very soon.
5669 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5670 // remove ranges for those requests that won't have a replacement
5671 final NetworkAgentInfo satisfier = nri.getSatisfier();
5672 if (null != satisfier) {
5673 try {
paulhu0e79d952021-06-09 16:11:35 +08005674 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5675 satisfier.network.getNetId(),
5676 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005677 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005678 } catch (RemoteException e) {
5679 loge("Exception setting network preference default network", e);
5680 }
5681 }
5682 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005683
Junyu Lai00d92df2022-07-05 11:01:52 +08005684 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005685 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005686 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005687
5688 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005689 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005690 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005691 }
5692 }
5693
Chalard Jean0354d8c2021-01-12 10:58:56 +09005694 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5695 // needed for this offer.
5696 for (final NetworkOfferInfo noi : mNetworkOffers) {
5697 for (final NetworkRequest req : nri.mRequests) {
5698 if (req.isRequest() && noi.offer.neededFor(req)) {
5699 noi.offer.onNetworkUnneeded(req);
5700 }
5701 }
5702 }
James Mattisa076c532020-12-02 14:12:41 -08005703 }
5704
James Mattis3ce3d3c2021-02-09 18:18:28 -08005705 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5706 for (final NetworkRequestInfo nri : nris) {
5707 if (mDefaultRequest == nri) {
5708 // Make sure we never remove the default request.
5709 continue;
5710 }
5711 handleRemoveNetworkRequest(nri);
5712 }
5713 }
5714
James Mattisa076c532020-12-02 14:12:41 -08005715 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5716 // listens don't have a singular affected Network. Check all networks to see
5717 // if this listen request applies and remove it.
5718 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5719 nai.removeRequest(req.requestId);
5720 if (req.networkCapabilities.hasSignalStrength()
5721 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5722 updateSignalStrengthThresholds(nai, "RELEASE", req);
5723 }
5724 }
5725 }
5726
5727 /**
5728 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5729 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5730 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5731 */
5732 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5733 boolean wasKept = false;
5734 final NetworkAgentInfo nai = nri.getSatisfier();
5735 if (nai != null) {
5736 final int requestLegacyType = nri.getActiveRequest().legacyType;
5737 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5738 nai.removeRequest(nri.getActiveRequest().requestId);
5739 if (VDBG || DDBG) {
5740 log(" Removing from current network " + nai.toShortString()
5741 + ", leaving " + nai.numNetworkRequests() + " requests.");
5742 }
5743 // If there are still lingered requests on this network, don't tear it down,
5744 // but resume lingering instead.
5745 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005746 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005747 notifyNetworkLosing(nai, now);
5748 }
5749 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5750 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5751 teardownUnneededNetwork(nai);
5752 } else {
5753 wasKept = true;
5754 }
James Mattisa076c532020-12-02 14:12:41 -08005755 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5756 // Went from foreground to background.
5757 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005758 }
5759
Erik Kline0c04b742016-07-07 16:50:58 +09005760 // Maintain the illusion. When this request arrived, we might have pretended
5761 // that a network connected to serve it, even though the network was already
5762 // connected. Now that this request has gone away, we might have to pretend
5763 // that the network disconnected. LegacyTypeTracker will generate that
5764 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005765 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005766 boolean doRemove = true;
5767 if (wasKept) {
5768 // check if any of the remaining requests for this network are for the
5769 // same legacy type - if so, don't remove the nai
5770 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5771 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005772 if (otherRequest.legacyType == requestLegacyType
5773 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005774 if (DBG) log(" still have other legacy request - leaving");
5775 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005776 }
5777 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005778 }
5779
Erik Kline0c04b742016-07-07 16:50:58 +09005780 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005781 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005782 }
5783 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005784 }
5785 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005786
Junyu Lai00d92df2022-07-05 11:01:52 +08005787 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai71b51532024-02-01 10:39:01 +08005788 return hasAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005789 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5790 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5791 }
5792
Lorenzo Colittid6459092016-07-04 12:55:44 +09005793 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005794 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005795 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005796 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005797 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005798 }
5799
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005800 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005801 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5802 enforceNetworkStackSettingsOrSetup();
5803 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5804 encodeBool(accept), encodeBool(always), network));
5805 }
5806
5807 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005808 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005809 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005810 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5811 }
5812
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005813 @Override
5814 public void setTestAllowBadWifiUntil(long timeMs) {
5815 enforceSettingsPermission();
5816 if (!Build.isDebuggable()) {
5817 throw new IllegalStateException("Does not support in non-debuggable build");
5818 }
5819
5820 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5821 throw new IllegalArgumentException("It should not exceed "
5822 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5823 }
5824
5825 mHandler.sendMessage(
5826 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5827 }
5828
chiachangwange0192a72023-02-06 13:25:01 +00005829 @Override
5830 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5831 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005832
5833 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5834 throw new IllegalArgumentException("Argument should not exceed "
5835 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5836 }
5837
5838 mHandler.sendMessage(
5839 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5840 }
5841
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005842 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5843 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5844 " accept=" + accept + " always=" + always);
5845
5846 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5847 if (nai == null) {
5848 // Nothing to do.
5849 return;
5850 }
5851
Chalard Jean254bd162022-08-25 13:04:51 +09005852 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005853 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005854 return;
5855 }
5856
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005857 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005858 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005859 }
5860
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005861 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5862 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005863 // If network becomes partial connectivity and user already accepted to use this
5864 // network, we should respect the user's option and don't need to popup the
5865 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005866 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005867 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005868 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005869 }
5870
5871 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005872 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005873 }
5874
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005875 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005876 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005877 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005878 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005879 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005880 }
5881
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005882 }
5883
lucaslin2240ef62019-03-12 13:08:03 +08005884 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5885 boolean always) {
5886 if (DBG) {
5887 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5888 + " always=" + always);
5889 }
5890
5891 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5892 if (nai == null) {
5893 // Nothing to do.
5894 return;
5895 }
5896
Chalard Jean254bd162022-08-25 13:04:51 +09005897 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005898 // The network validated while the dialog box was up. Take no action.
5899 return;
5900 }
5901
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005902 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5903 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005904 }
5905
5906 // TODO: Use the current design or save the user choice into IpMemoryStore.
5907 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005908 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005909 }
5910
5911 if (!accept) {
5912 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005913 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005914 // Tear down the network.
5915 teardownUnneededNetwork(nai);
5916 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005917 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5918 // result in a partial connectivity result which will be processed by
5919 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005920 //
5921 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5922 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005923 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005924 }
5925 }
5926
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005927 private void handleSetAvoidUnvalidated(Network network) {
5928 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005929 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005930 // Nothing to do. The network either disconnected or revalidated.
5931 return;
5932 }
Chalard Jean254bd162022-08-25 13:04:51 +09005933 if (0L == nai.getAvoidUnvalidated()) {
5934 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005935 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005936 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005937 }
5938 }
5939
Chalard Jean5fb43c72022-09-08 19:03:14 +09005940 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005941 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005942 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005943 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005944 }
5945
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005946 @Override
5947 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005948 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005949 mHandler.post(() -> {
5950 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5951 if (nai == null) return;
5952 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005953 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005954 });
5955 }
5956
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005957 /**
5958 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5959 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005960 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005961 * @param appExtras Bundle to use as intent extras for the captive portal application.
5962 * Must be treated as opaque to avoid preventing the captive portal app to
5963 * update its arguments.
5964 */
5965 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005966 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005967 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5968 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005969
5970 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5971 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005972 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5973 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005974 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5975
lucaslin75ff7022020-12-17 04:14:35 +08005976 final long token = Binder.clearCallingIdentity();
5977 try {
5978 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5979 } finally {
5980 Binder.restoreCallingIdentity(token);
5981 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005982 }
5983
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005984 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5985 private final Network mNetwork;
5986
5987 private CaptivePortalImpl(Network network) {
5988 mNetwork = network;
5989 }
5990
5991 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005992 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005993 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5994 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005995 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5996 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5997 // Since the network will be disconnected, skip notifying NetworkMonitor
5998 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005999 }
6000
Chiachang Wang938bfba2020-01-09 13:50:55 +08006001 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006002 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006003 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006004 }
6005
6006 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08006007 public void appRequest(final int request) {
6008 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
6009 if (nm == null) return;
6010
6011 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Junyu Lai71b51532024-02-01 10:39:01 +08006012 hasNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006013 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08006014 }
6015 }
6016
6017 @Nullable
6018 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
6019 // getNetworkAgentInfoForNetwork is thread-safe
6020 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6021 if (nai == null) return null;
6022
6023 // nai.networkMonitor() is thread-safe
6024 return nai.networkMonitor();
6025 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006026 }
6027
Hugo Benichic9048bc2016-09-14 23:23:08 +00006028 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006029 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09006030 }
6031
Chalard Jean020b93a2022-09-01 13:20:14 +09006032 private boolean activelyPreferBadWifi() {
6033 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
6034 }
6035
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09006036 /**
6037 * Return whether the device should maintain continuous, working connectivity by switching away
6038 * from WiFi networks having no connectivity.
6039 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
6040 */
6041 public boolean shouldAvoidBadWifi() {
Junyu Lai71b51532024-02-01 10:39:01 +08006042 if (!hasNetworkStackPermission()) {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09006043 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
6044 }
6045 return avoidBadWifi();
6046 }
6047
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006048 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09006049 ensureRunningOnConnectivityServiceThread();
6050 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09006051 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006052 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09006053 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09006054 if (avoidBadWifi) {
6055 // If the device is now avoiding bad wifi, remove notifications that might have
6056 // been put up when the device didn't.
6057 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
6058 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006059 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09006060 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
6061 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
6062 for (final NetworkOfferInfo noi : offersToUpdate) {
6063 updateOfferScore(noi.offer);
6064 }
Chalard Jean020b93a2022-09-01 13:20:14 +09006065 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09006066 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006067 }
6068
Erik Kline95ecfee2016-10-02 18:02:14 +09006069 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006070 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006071 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006072 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006073 if (!configRestrict) {
6074 pw.println("Bad Wi-Fi avoidance: unrestricted");
6075 return;
6076 }
6077
6078 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
6079 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09006080 pw.println("Config restrict: " + configRestrict);
6081 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006082
Chalard Jeane0fdea32022-09-14 21:44:22 +09006083 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006084 String description;
6085 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09006086 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006087 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006088 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006089 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006090 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006091 description = "avoid";
6092 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09006093 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006094 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09006095 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00006096
6097 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
6098 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09006099 if (null == configValue) {
6100 description = "unset";
6101 } else if (configValue) {
6102 description = "force true";
6103 } else {
6104 description = "force false";
6105 }
6106 pw.println("Actively prefer bad wifi conf: " + description);
6107 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006108 pw.println("Network overrides:");
6109 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09006110 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09006111 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09006112 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006113 }
6114 }
6115 pw.decreaseIndent();
6116 pw.decreaseIndent();
6117 }
6118
paulhu7746e4e2020-06-09 19:07:03 +08006119 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
6120 // unify the method.
6121 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
6122 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
6123 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
6124 return settingsComponent != null
6125 ? settingsComponent.getPackageName() : "com.android.settings";
6126 }
6127
lucaslinb1e8e382019-01-24 15:55:30 +08006128 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006129 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006130 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006131 switch (type) {
6132 case NO_INTERNET:
6133 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006134 // High priority because it is only displayed for explicitly selected networks.
6135 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006136 break;
lucasline117e2e2019-10-22 18:27:33 +08006137 case PRIVATE_DNS_BROKEN:
6138 action = Settings.ACTION_WIRELESS_SETTINGS;
6139 // High priority because we should let user know why there is no internet.
6140 highPriority = true;
6141 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006142 case LOST_INTERNET:
6143 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006144 // High priority because it could help the user avoid unexpected data usage.
6145 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006146 break;
lucaslin2240ef62019-03-12 13:08:03 +08006147 case PARTIAL_CONNECTIVITY:
6148 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006149 // Don't bother the user with a high-priority notification if the network was not
6150 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006151 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006152 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006153 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006154 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006155 return;
6156 }
6157
6158 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006159 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006160 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006161 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006162 // Some OEMs have their own Settings package. Thus, need to get the current using
6163 // Settings package name instead of just use default name "com.android.settings".
6164 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6165 intent.setClassName(settingsPkgName,
6166 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006167 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006168
paulhu2af50222020-10-11 22:52:27 +08006169 PendingIntent pendingIntent = PendingIntent.getActivity(
6170 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006171 0 /* requestCode */,
6172 intent,
paulhu2af50222020-10-11 22:52:27 +08006173 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006174
Serik Beketayevec8ad212020-12-07 22:43:07 -08006175 mNotifier.showNotification(
6176 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006177 }
6178
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006179 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6180 // Don't prompt if the network is validated, and don't prompt on captive portals
6181 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006182 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006183 return false;
6184 }
6185
6186 // If a network has partial connectivity, always prompt unless the user has already accepted
6187 // partial connectivity and selected don't ask again. This ensures that if the device
6188 // automatically connects to a network that has partial Internet access, the user will
6189 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006190 // because we have prompted them.
6191 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006192 return true;
6193 }
6194
6195 // If a network has no Internet access, only prompt if the network was explicitly selected
6196 // and if the user has not already told us to use the network regardless of whether it
6197 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006198 if (nai.networkAgentConfig.explicitlySelected
6199 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006200 return true;
6201 }
6202
6203 return false;
6204 }
6205
Chalard Jean5fb43c72022-09-08 19:03:14 +09006206 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6207 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006208
Chalard Jean5fb43c72022-09-08 19:03:14 +09006209 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6210 if (null == nai) return;
6211
6212 if (nai.setEvaluated()) {
6213 // If setEvaluated() returned true, the network never had any form of connectivity.
6214 // This may have an impact on request matching if bad WiFi avoidance is off and the
6215 // network was found not to have Internet access.
6216 nai.updateScoreForNetworkAgentUpdate();
6217 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006218
6219 // Also, if this is WiFi and it should be preferred actively, now is the time to
6220 // prompt the user that they walked past and connected to a bad WiFi.
6221 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6222 && !avoidBadWifi()
6223 && activelyPreferBadWifi()) {
6224 // The notification will be removed if the network validates or disconnects.
6225 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6226 return;
6227 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006228 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006229
Chalard Jean5fb43c72022-09-08 19:03:14 +09006230 if (!shouldPromptUnvalidated(nai)) return;
6231
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006232 // Stop automatically reconnecting to this network in the future. Automatically connecting
6233 // to a network that provides no or limited connectivity is not useful, because the user
6234 // cannot use that network except through the notification shown by this method, and the
6235 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006236 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006237
Chalard Jean254bd162022-08-25 13:04:51 +09006238 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006239 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006240 } else {
6241 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6242 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006243 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006244
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006245 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6246 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006247 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006248
lucaslin2240ef62019-03-12 13:08:03 +08006249 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6250 return;
6251 }
6252
6253 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006254 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006255 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006256 }
6257
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006258 @Override
6259 public int getMultipathPreference(Network network) {
6260 enforceAccessPermission();
6261
6262 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006263 if (nai != null && nai.networkCapabilities
6264 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006265 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6266 }
6267
Aaron Huang9a57acf2020-12-08 10:03:29 +08006268 final NetworkPolicyManager netPolicyManager =
6269 mContext.getSystemService(NetworkPolicyManager.class);
6270
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006271 final long token = Binder.clearCallingIdentity();
6272 final int networkPreference;
6273 try {
6274 networkPreference = netPolicyManager.getMultipathPreference(network);
6275 } finally {
6276 Binder.restoreCallingIdentity(token);
6277 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006278 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006279 return networkPreference;
6280 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006281 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6282 }
6283
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006284 @Override
6285 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006286 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006287 }
6288
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006289 private class InternalHandler extends Handler {
6290 public InternalHandler(Looper looper) {
6291 super(looper);
6292 }
6293
6294 @Override
6295 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006296 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006297 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006298 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006299 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006300 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006301 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006302 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006303 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006304 break;
6305 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006306 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006307 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006308 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006309 break;
6310 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006311 case EVENT_REGISTER_NETWORK_PROVIDER: {
6312 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006313 break;
6314 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006315 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6316 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006317 break;
6318 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006319 case EVENT_REGISTER_NETWORK_OFFER: {
6320 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6321 break;
6322 }
6323 case EVENT_UNREGISTER_NETWORK_OFFER: {
6324 final NetworkOfferInfo offer =
6325 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6326 if (null != offer) {
6327 handleUnregisterNetworkOffer(offer);
6328 }
6329 break;
6330 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006331 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006332 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6333 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6334 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006335 break;
6336 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006337 case EVENT_REGISTER_NETWORK_REQUEST:
6338 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006339 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006340 break;
6341 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006342 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6343 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006344 handleRegisterNetworkRequestWithIntent(msg);
6345 break;
6346 }
Erik Kline155a59a2015-11-25 12:49:38 +09006347 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6348 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6349 handleTimedOutNetworkRequest(nri);
6350 break;
6351 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006352 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6353 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6354 break;
6355 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006356 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006357 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6358 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006359 break;
6360 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006361 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006362 Network network = (Network) msg.obj;
6363 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006364 break;
6365 }
lucaslin2240ef62019-03-12 13:08:03 +08006366 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6367 Network network = (Network) msg.obj;
6368 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6369 toBool(msg.arg2));
6370 break;
6371 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006372 case EVENT_SET_AVOID_UNVALIDATED: {
6373 handleSetAvoidUnvalidated((Network) msg.obj);
6374 break;
6375 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006376 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6377 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006378 break;
6379 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006380 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6381 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006382 break;
6383 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006384 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6385 // handler thread.
6386 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006387 mKeepaliveTracker.handleStartKeepalive(msg);
6388 break;
6389 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006390 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006391 final AutomaticOnOffKeepalive ki =
6392 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6393 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006394
chiachangwang676c84e2023-02-14 09:22:05 +00006395 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006396 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006397 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006398 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006399 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6400 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006401 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6402 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006403 }
6404 }
6405
6406 // If the network no longer exists, then the keepalive should have been
6407 // cleaned up already. There is no point trying to resume keepalives.
6408 if (!networkFound) return;
6409
chiachangwang676c84e2023-02-14 09:22:05 +00006410 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006411 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wangac2e8f32024-01-18 12:55:11 +00006412 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006413 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006414 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006415 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006416 }
6417 break;
6418 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006419 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006420 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006421 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6422 (IBinder) msg.obj);
6423 if (ki == null) {
6424 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006425 return;
6426 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006427 final int reason = msg.arg2;
6428 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006429 break;
6430 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006431 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6432 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6433 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006434 break;
6435 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006436 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6437 handlePrivateDnsSettingsChanged();
6438 break;
dalyk1720e542018-03-05 12:42:22 -05006439 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6440 handlePrivateDnsValidationUpdate(
6441 (PrivateDnsValidationUpdate) msg.obj);
6442 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006443 case EVENT_UID_BLOCKED_REASON_CHANGED:
6444 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006445 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006446 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6447 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6448 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006449 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006450 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6451 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006452 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006453 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006454 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006455 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006456 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6457 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006458 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006459 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006460 }
lucaslin1193a5d2021-01-21 02:04:15 +08006461 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006462 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006463 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006464 break;
paulhu51f77dc2021-06-07 02:34:20 +00006465 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6466 handleMobileDataPreferredUidsChanged();
6467 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006468 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6469 final long timeMs = ((Long) msg.obj).longValue();
6470 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6471 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006472 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6473 handleIngressRateLimitChanged();
6474 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006475 case EVENT_USER_DOES_NOT_WANT:
6476 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6477 if (nai == null) break;
6478 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006479 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006480 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006481 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6482 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6483 break;
chiachangwange0192a72023-02-06 13:25:01 +00006484 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6485 final long time = ((Long) msg.obj).longValue();
6486 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6487 break;
6488 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006489 case EVENT_UID_FROZEN_STATE_CHANGED:
6490 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6491 handleFrozenUids(args.mUids, args.mFrozenStates);
6492 break;
Ying Xu7cabd322024-01-15 18:40:15 -08006493 case EVENT_UID_CARRIER_PRIVILEGES_LOST:
Ying Xu0d06b942024-02-09 21:04:08 -08006494 handleUidCarrierPrivilegesLost(msg.arg1, msg.arg2);
Ying Xu7cabd322024-01-15 18:40:15 -08006495 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006496 }
6497 }
6498 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006499
Lorenzo Colittid6459092016-07-04 12:55:44 +09006500 @Override
markchien5776f962019-12-16 20:15:20 +08006501 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006502 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006503 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006504 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6505 Context.TETHERING_SERVICE);
6506 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006507 }
6508
Lorenzo Colittid6459092016-07-04 12:55:44 +09006509 @Override
markchien5776f962019-12-16 20:15:20 +08006510 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006511 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006512 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006513 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6514 Context.TETHERING_SERVICE);
6515 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006516 }
6517
Lorenzo Colittid6459092016-07-04 12:55:44 +09006518 @Override
markchien5776f962019-12-16 20:15:20 +08006519 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006520 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006521 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006522 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6523 Context.TETHERING_SERVICE);
6524 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006525 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006526
markchien5776f962019-12-16 20:15:20 +08006527
Lorenzo Colittid6459092016-07-04 12:55:44 +09006528 @Override
markchien5776f962019-12-16 20:15:20 +08006529 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006530 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006531 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006532 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6533 Context.TETHERING_SERVICE);
6534
6535 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006536 }
6537
Lorenzo Colittid6459092016-07-04 12:55:44 +09006538 @Override
markchien5776f962019-12-16 20:15:20 +08006539 @Deprecated
6540 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006541 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006542 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6543 Context.TETHERING_SERVICE);
6544
6545 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006546 }
6547
Udam Saini8f7d6a72017-06-07 12:06:28 -07006548 @Override
markchien5776f962019-12-16 20:15:20 +08006549 @Deprecated
6550 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006551 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006552 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6553 Context.TETHERING_SERVICE);
6554 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006555 }
6556
Robert Greenwalte0b00512014-07-02 09:59:16 -07006557 // Called when we lose the default network and have no replacement yet.
6558 // This will automatically be cleared after X seconds or a new default network
6559 // becomes CONNECTED, whichever happens first. The timer is started by the
6560 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006561 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006562 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006563 if (mNetTransitionWakeLock.isHeld()) {
6564 return;
6565 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006566 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006567 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6568 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006569 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006570 mWakelockLogs.log("ACQUIRE for " + forWhom);
6571 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006572 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006573 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006574 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006575 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006576
Hugo Benichi471b62a2017-03-30 23:18:10 +09006577 // Called when we gain a new default network to release the network transition wakelock in a
6578 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6579 // message is cancelled.
6580 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006581 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006582 if (!mNetTransitionWakeLock.isHeld()) {
6583 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006584 }
6585 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006586 // Cancel self timeout on wakelock hold.
6587 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6588 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6589 mHandler.sendMessageDelayed(msg, 1000);
6590 }
6591
6592 // Called when either message of ensureNetworkTransitionWakelock or
6593 // scheduleReleaseNetworkTransitionWakelock is processed.
6594 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6595 String event = eventName(eventId);
6596 synchronized (this) {
6597 if (!mNetTransitionWakeLock.isHeld()) {
6598 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006599 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006600 return;
6601 }
6602 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006603 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6604 mTotalWakelockDurationMs += lockDuration;
6605 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6606 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006607 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006608 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006609 }
6610
Robert Greenwalt986c7412010-09-08 15:24:47 -07006611 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006612 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006613 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006614 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006615 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006616 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006617 }
6618
Lorenzo Colittid6459092016-07-04 12:55:44 +09006619 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006620 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006621 enforceAccessPermission();
6622 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006623 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006624 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006625
6626 final NetworkAgentInfo nai;
6627 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006628 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006629 } else {
6630 nai = getNetworkAgentInfoForNetwork(network);
6631 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006632
6633 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006634 mHandler.obtainMessage(
6635 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006636 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006637
Hugo Benichid6b510a2017-04-06 17:22:18 +09006638 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006639 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006640 if (nai == null
6641 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006642 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006643 return;
6644 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006645 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006646 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006647 mConnectivityDiagnosticsHandler.sendMessage(
6648 mConnectivityDiagnosticsHandler.obtainMessage(
6649 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6650 new ReportedNetworkConnectivityInfo(
6651 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006652 return;
6653 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006654 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006655 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006656 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006657 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006658 // Validating a network that has not yet connected could result in a call to
6659 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006660 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006661 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006662 }
paulhu7aeba372020-12-30 00:42:19 +08006663 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6664 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006665 return;
6666 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006667
6668 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6669 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6670 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6671 // completed.
6672 mConnectivityDiagnosticsHandler.sendMessage(
6673 mConnectivityDiagnosticsHandler.obtainMessage(
6674 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6675 new ReportedNetworkConnectivityInfo(
6676 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006677 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006678 }
6679
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006680 // TODO: call into netd.
6681 private boolean queryUserAccess(int uid, Network network) {
6682 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6683 if (nai == null) return false;
6684
6685 // Any UID can use its default network.
6686 if (nai == getDefaultNetworkForUid(uid)) return true;
6687
6688 // Privileged apps can use any network.
6689 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6690 return true;
6691 }
6692
6693 // An unprivileged UID can use a VPN iff the VPN applies to it.
6694 if (nai.isVPN()) {
6695 return nai.networkCapabilities.appliesToUid(uid);
6696 }
6697
6698 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6699 // sockets, i.e., if it is the owner.
6700 final NetworkAgentInfo vpn = getVpnForUid(uid);
6701 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6702 && uid != vpn.networkCapabilities.getOwnerUid()) {
6703 return false;
6704 }
6705
6706 // The UID's permission must be at least sufficient for the network. Since the restricted
6707 // permission was already checked above, that just leaves background networks.
6708 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6709 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6710 }
6711
6712 // Unrestricted network. Anyone gets to use it.
6713 return true;
6714 }
6715
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006716 /**
6717 * Returns information about the proxy a certain network is using. If given a null network, it
6718 * it will return the proxy for the bound network for the caller app or the default proxy if
6719 * none.
6720 *
6721 * @param network the network we want to get the proxy information for.
6722 * @return Proxy information if a network has a proxy configured, or otherwise null.
6723 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006724 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006725 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006726 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006727 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006728 if (network == null) {
6729 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006730 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006731 true);
6732 if (activeNetwork == null) {
6733 return null;
6734 }
6735 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006736 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006737 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6738 // caller may not have.
6739 return getLinkPropertiesProxyInfo(network);
6740 }
6741 // No proxy info available if the calling UID does not have network access.
6742 return null;
6743 }
6744
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006745
6746 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006747 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6748 if (nai == null) return null;
6749 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006750 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6751 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006752 }
6753 }
6754
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006755 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006756 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006757 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006758 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006759 }
6760
Chalard Jean777e2e52018-06-07 18:02:37 +09006761 @Override
6762 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006763 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006764 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006765 }
6766
Aaron Huang9fe47be2021-06-08 13:11:45 +08006767 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006768 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006769 final NetworkAgentInfo nai = getDefaultNetwork();
6770 // TODO : this method should check that net == nai.network, unfortunately at this point
6771 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6772 // is only ever installed on the default network so in practice this is okay.
6773 if (null == nai) return;
6774 // PAC proxies only work on the default network. Therefore, only the default network
6775 // should have its link properties fixed up for PAC proxies.
6776 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6777 if (nai.everConnected()) {
6778 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6779 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006780 }
6781
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006782 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6783 // when any network changes proxy.
6784 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6785 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006786 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6787 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006788 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6789
Chalard Jean7d97afc2018-06-07 17:41:29 +09006790 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006791 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006792 }
6793 }
6794
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006795 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006796 final private HashMap<Uri, Integer> mUriEventMap;
6797 final private Context mContext;
6798 final private Handler mHandler;
6799
6800 SettingsObserver(Context context, Handler handler) {
6801 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006802 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006803 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006804 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006805 }
6806
Erik Kline05f2b402015-04-30 12:58:40 +09006807 void observe(Uri uri, int what) {
6808 mUriEventMap.put(uri, what);
6809 final ContentResolver resolver = mContext.getContentResolver();
6810 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006811 }
6812
6813 @Override
6814 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006815 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006816 }
6817
6818 @Override
6819 public void onChange(boolean selfChange, Uri uri) {
6820 final Integer what = mUriEventMap.get(uri);
6821 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006822 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006823 } else {
6824 loge("No matching event to send for URI=" + uri);
6825 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006826 }
6827 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006828
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006829 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006830 Log.d(TAG, s);
6831 }
6832
6833 private static void logw(String s) {
6834 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006835 }
6836
Daniel Brightf9e945b2020-06-15 16:10:01 -07006837 private static void logwtf(String s) {
6838 Log.wtf(TAG, s);
6839 }
6840
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006841 private static void logwtf(String s, Throwable t) {
6842 Log.wtf(TAG, s, t);
6843 }
6844
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006845 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006846 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006847 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006848
Hugo Benichi39621362017-02-11 17:04:43 +09006849 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006850 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006851 }
6852
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006853 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006854 * Return the information of all ongoing VPNs.
6855 *
6856 * <p>This method is used to update NetworkStatsService.
6857 *
6858 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006859 */
junyulai2050bed2021-01-23 09:46:34 +08006860 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006861 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006862 if (mLockdownEnabled) {
6863 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006864 }
junyulai2050bed2021-01-23 09:46:34 +08006865 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006866 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006867 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006868 if (info != null) {
6869 infoList.add(info);
6870 }
6871 }
junyulai2050bed2021-01-23 09:46:34 +08006872 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006873 }
6874
6875 /**
6876 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006877 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006878 */
junyulai2050bed2021-01-23 09:46:34 +08006879 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006880 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006881 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6882 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006883 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6884 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6885 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006886 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6887 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006888 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006889 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006890 }
6891 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006892
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006893 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006894
6895 List<String> interfaces = new ArrayList<>();
6896 for (Network network : underlyingNetworks) {
6897 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6898 if (underlyingNai == null) continue;
6899 LinkProperties lp = underlyingNai.linkProperties;
6900 for (String iface : lp.getAllInterfaceNames()) {
6901 if (!TextUtils.isEmpty(iface)) {
6902 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006903 }
6904 }
Benedict Wong34857f82019-06-12 17:46:15 +00006905 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006906
6907 if (interfaces.isEmpty()) return null;
6908
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006909 // Must be non-null or NetworkStatsService will crash.
6910 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6911 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006912 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006913 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006914
junyulai2050bed2021-01-23 09:46:34 +08006915 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6916 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006917 }
6918
James Mattisd31bdfa2020-12-23 16:37:26 -08006919 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006920 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6921 Network[] underlyingNetworks) {
6922 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006923 if (underlyingNetworks == null && defaultNetwork != null) {
6924 // null underlying networks means to track the default.
6925 underlyingNetworks = new Network[] { defaultNetwork };
6926 }
6927 return underlyingNetworks;
6928 }
6929
6930 // Returns true iff |network| is an underlying network of |nai|.
6931 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6932 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6933 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006934 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006935 final Network[] underlying = underlyingNetworksOrDefault(
6936 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006937 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006938 }
6939
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006940 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006941 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006942 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006943 * When underlying networks change, such networks may have to update capabilities to reflect
6944 * things like the metered bit, their transports, and so on. The capabilities are calculated
6945 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006946 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006947 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006948 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006949 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006950 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006951 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006952 }
6953 }
6954 }
6955
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006956 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6957 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6958 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6959 // a VPN is not up.
6960 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6961 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6962 for (UidRange range : blockedUidRanges) {
6963 if (range.contains(uid)) return true;
6964 }
6965 return false;
6966 }
6967
6968 @Override
6969 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006970 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006971 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6972 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6973 }
6974
6975 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6976 if (DBG) {
6977 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6978 + Arrays.toString(ranges));
6979 }
6980 // Cannot use a Set since the list of UID ranges might contain duplicates.
6981 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6982 for (int i = 0; i < ranges.length; i++) {
6983 if (requireVpn) {
6984 newVpnBlockedUidRanges.add(ranges[i]);
6985 } else {
6986 newVpnBlockedUidRanges.remove(ranges[i]);
6987 }
6988 }
6989
6990 try {
6991 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6992 } catch (RemoteException | ServiceSpecificException e) {
6993 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6994 + Arrays.toString(ranges) + "): netd command failed: " + e);
6995 }
6996
Chalard Jeandf29a852023-05-29 17:02:43 +09006997 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006998 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6999 }
7000
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007001 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
7002 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00007003 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
7004 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007005 }
7006
7007 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
7008 }
7009
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07007010 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007011 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08007012 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007013 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01007014 }
7015
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007016 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
7017 return mLockdownEnabled
7018 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
7019 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00007020 }
7021
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007022 private NetworkAgentInfo getLegacyLockdownNai() {
7023 if (!mLockdownEnabled) {
7024 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00007025 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007026 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007027 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
7028 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00007029
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007030 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007031 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
7032 // a local variable. There is no need to make a copy because its contents cannot change.
7033 final Network[] underlying = nai.declaredUnderlyingNetworks;
7034 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007035 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007036 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007037
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007038 // The legacy lockdown VPN always uses the default network.
7039 // If the VPN's underlying network is no longer the current default network, it means that
7040 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007041 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
7042 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007043 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007044 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007045 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007046 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007047
7048 return nai;
7049 };
7050
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007051 // TODO: move all callers to filterForLegacyLockdown and delete this method.
7052 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
7053 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007054 private DetailedState getLegacyLockdownState(DetailedState origState) {
7055 if (origState != DetailedState.CONNECTED) {
7056 return origState;
7057 }
7058 return (mLockdownEnabled && getLegacyLockdownNai() == null)
7059 ? DetailedState.CONNECTING
7060 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007061 }
7062
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007063 private void filterForLegacyLockdown(NetworkInfo ni) {
7064 if (!mLockdownEnabled || !ni.isConnected()) return;
7065 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
7066 // state of its VPN. This is to ensure that when an underlying network connects, apps will
7067 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
7068 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
7069 // network, this time with a state of CONNECTED.
7070 //
7071 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
7072 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
7073 // is not too far off the truth, since an always-on VPN, when not connected, is always
7074 // trying to reconnect.
7075 if (getLegacyLockdownNai() == null) {
7076 ni.setDetailedState(DetailedState.CONNECTING, "", null);
7077 }
7078 }
7079
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007080 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07007081 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04007082 String action) {
paulhu8e96a752019-08-12 16:25:11 +08007083 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09007084 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
7085 return;
7086 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04007087 final long ident = Binder.clearCallingIdentity();
7088 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09007089 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007090 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09007091 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04007092 } finally {
7093 Binder.restoreCallingIdentity(ident);
7094 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07007095 }
Wink Savillecb117d32013-08-29 14:57:08 -07007096
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007097 @Override
7098 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01007099 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007100 final long ident = Binder.clearCallingIdentity();
7101 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007102 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09007103 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007104 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
7105 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08007106 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007107 } finally {
7108 Binder.restoreCallingIdentity(ident);
7109 }
7110 }
7111
James Mattis02220e22021-03-13 19:27:21 -08007112 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08007113 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7114 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7115 }
Chalard Jeane0abd522023-01-23 16:47:43 +09007116 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007117 }
7118
James Mattis02220e22021-03-13 19:27:21 -08007119 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09007120 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007121 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08007122 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
7123 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09007124 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08007125 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7126 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7127 }
junyulaid91e7052020-08-28 13:44:33 +08007128 }
7129
James Mattis02220e22021-03-13 19:27:21 -08007130 private void onPackageChanged(@NonNull final String packageName) {
7131 // This is necessary in case a package is added or removed, but also when it's replaced to
7132 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
7133 // as one in the preferences, then it should follow the same routing as that other package,
7134 // which means updating the rules is never to be needed in this case (whether it joins or
7135 // leaves a UID with a preference).
7136 if (isMappedInOemNetworkPreference(packageName)) {
7137 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7138 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007139
7140 // Invalidates cache entry when the package is updated.
7141 synchronized (mSelfCertifiedCapabilityCache) {
7142 mSelfCertifiedCapabilityCache.remove(packageName);
7143 }
James Mattis02220e22021-03-13 19:27:21 -08007144 }
7145
7146 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007147 @Override
7148 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007149 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007150 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007151 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007152
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007153 // User should be filled for below intents, check the existence.
7154 if (user == null) {
7155 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7156 return;
7157 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007158
Lorenzo Colitticd675292021-02-04 17:32:07 +09007159 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007160 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007161 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007162 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007163 } else {
junyulaid91e7052020-08-28 13:44:33 +08007164 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007165 }
7166 }
7167 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007168
James Mattis02220e22021-03-13 19:27:21 -08007169 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7170 @Override
7171 public void onReceive(Context context, Intent intent) {
7172 ensureRunningOnConnectivityServiceThread();
7173 switch (intent.getAction()) {
7174 case Intent.ACTION_PACKAGE_ADDED:
7175 case Intent.ACTION_PACKAGE_REMOVED:
7176 case Intent.ACTION_PACKAGE_REPLACED:
7177 onPackageChanged(intent.getData().getSchemeSpecificPart());
7178 break;
7179 default:
7180 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7181 }
7182 }
7183 };
7184
Junyu Lai38c75032023-12-04 07:52:19 +00007185 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
7186 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
7187 @Override
7188 public void onReceive(Context context, Intent intent) {
7189 if (mDeps.isAtLeastV()) {
7190 throw new IllegalStateException(
7191 "data saver status should be updated from platform");
7192 }
7193 ensureRunningOnConnectivityServiceThread();
7194 switch (intent.getAction()) {
7195 case ACTION_RESTRICT_BACKGROUND_CHANGED:
7196 // If the uid is present in the deny list, the API will consistently
7197 // return ENABLED. To retrieve the global switch status, the system
7198 // uid is chosen because it will never be included in the deny list.
7199 final int dataSaverForSystemUid =
7200 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
7201 final boolean isDataSaverEnabled = (dataSaverForSystemUid
7202 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
7203 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
7204 break;
7205 default:
7206 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7207 }
7208 }
7209 };
7210
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007211 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007212 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007213
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007214 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007215 public final String name;
7216 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007217 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007218 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007219
lifraf3a3492021-03-10 13:58:14 +08007220 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7221 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007222 this.name = name;
7223 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007224 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007225 mDeathRecipient = deathRecipient;
7226
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007227 if (mDeathRecipient == null) {
7228 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007229 }
7230 }
7231
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007232 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007233 try {
7234 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7235 } catch (RemoteException e) {
7236 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007237 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007238 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007239 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007240
James Mattis4fce5d12020-11-12 15:53:42 -08007241 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7242 for (int i = 0; i < requests.size(); i++) {
7243 ensureNetworkRequestHasType(requests.get(i));
7244 }
7245 }
7246
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007247 private void ensureNetworkRequestHasType(NetworkRequest request) {
7248 if (request.type == NetworkRequest.Type.NONE) {
7249 throw new IllegalArgumentException(
7250 "All NetworkRequests in ConnectivityService must have a type");
7251 }
7252 }
7253
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007254 /**
7255 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007256 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007257 */
James Mattis258ea3c2020-11-15 15:04:40 -08007258 @VisibleForTesting
7259 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007260 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7261 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007262 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007263
James Mattisa076c532020-12-02 14:12:41 -08007264 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7265 void setSatisfier(
7266 @Nullable final NetworkAgentInfo satisfier,
7267 @Nullable final NetworkRequest activeRequest) {
7268 mSatisfier = satisfier;
7269 mActiveRequest = activeRequest;
7270 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007271
James Mattisd31bdfa2020-12-23 16:37:26 -08007272 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007273 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007274 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007275 private NetworkAgentInfo mSatisfier;
7276 NetworkAgentInfo getSatisfier() {
7277 return mSatisfier;
7278 }
7279
7280 // The request in mRequests assigned to a network agent. This is null if none of the
7281 // requests in mRequests can be satisfied. This member has the constraint of only being
7282 // accessible on the handler thread.
7283 @Nullable
7284 private NetworkRequest mActiveRequest;
7285 NetworkRequest getActiveRequest() {
7286 return mActiveRequest;
7287 }
7288
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007289 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007290 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007291 @Nullable
7292 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007293
7294 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007295 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007296 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007297 final int mPid;
7298 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007299 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007300 @Nullable
7301 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007302
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007303 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007304 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007305
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007306 // Effective UID of this request. This is different from mUid when a privileged process
7307 // files a request on behalf of another UID. This UID is used to determine blocked status,
7308 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7309 // maximum limit of registered callbacks per UID.
7310 final int mAsUid;
7311
paulhu48291862021-07-14 14:53:57 +08007312 // Preference order of this request.
7313 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007314
James Mattis3ce3d3c2021-02-09 18:18:28 -08007315 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7316 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7317 // maintained for keying off of. This is only a concern when the original nri
7318 // mNetworkRequests changes which happens currently for apps that register callbacks to
7319 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7320 // that match the per-app default nri that currently tracks the calling app's uid so that
7321 // callbacks are fired at the appropriate time. When the callbacks fire,
7322 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7323 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7324 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7325 @NonNull
7326 private final NetworkRequest mNetworkRequestForCallback;
7327 NetworkRequest getNetworkRequestForCallback() {
7328 return mNetworkRequestForCallback;
7329 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007330
James Mattisd31bdfa2020-12-23 16:37:26 -08007331 /**
7332 * Get the list of UIDs this nri applies to.
7333 */
7334 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007335 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007336 // networkCapabilities.getUids() returns a defensive copy.
7337 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007338 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7339 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007340 }
7341
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007342 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7343 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007344 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007345 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007346 }
7347
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007348 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007349 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007350 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007351 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007352 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007353 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007354 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007355 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007356 mBinder = null;
7357 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007358 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007359 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007360 mPerUidCounter = getRequestCounter(this);
7361 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007362 /**
7363 * Location sensitive data not included in pending intent. Only included in
7364 * {@link NetworkCallback}.
7365 */
7366 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007367 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007368 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007369 }
7370
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007371 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007372 @Nullable final IBinder binder,
7373 @NetworkCallback.Flag int callbackFlags,
7374 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007375 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7376 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007377 }
7378
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007379 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007380 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007381 @Nullable final IBinder binder,
7382 @NetworkCallback.Flag int callbackFlags,
7383 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007384 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007385 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007386 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007387 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007388 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007389 mBinder = binder;
7390 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007391 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007392 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007393 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007394 mPerUidCounter = getRequestCounter(this);
7395 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007396 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007397 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007398 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007399 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007400 }
7401
James Mattis3ce3d3c2021-02-09 18:18:28 -08007402 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7403 @NonNull final List<NetworkRequest> r) {
7404 super();
7405 ensureAllNetworkRequestsHaveType(r);
7406 mRequests = initializeRequests(r);
7407 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007408 final NetworkAgentInfo satisfier = nri.getSatisfier();
7409 if (null != satisfier) {
7410 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7411 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007412 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007413 // As this code creates a new NRI with a new set of requests, figure out which of
7414 // the list of requests should be the active request. It is always the first
7415 // request of the list that can be satisfied by the satisfier since the order of
7416 // requests is a priority order.
7417 // Note even in the presence of a satisfier there may not be an active request,
7418 // when the satisfier is the no-service network.
7419 NetworkRequest activeRequest = null;
7420 for (final NetworkRequest candidate : r) {
7421 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7422 activeRequest = candidate;
7423 break;
7424 }
7425 }
7426 setSatisfier(satisfier, activeRequest);
7427 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007428 mMessenger = nri.mMessenger;
7429 mBinder = nri.mBinder;
7430 mPid = nri.mPid;
7431 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007432 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007433 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007434 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007435 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007436 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007437 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007438 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007439 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007440 }
7441
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007442 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007443 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007444 }
7445
paulhue9913722021-05-26 15:19:20 +08007446 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007447 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007448 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007449 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007450 }
7451
James Mattis2516da32021-01-31 17:06:19 -08007452 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7453 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7454 // false.
7455 boolean isBeingSatisfied() {
7456 return (null != mSatisfier && null != mActiveRequest);
7457 }
7458
James Mattis3d229892020-11-16 16:46:28 -08007459 boolean isMultilayerRequest() {
7460 return mRequests.size() > 1;
7461 }
7462
James Mattis45d81842021-01-10 14:24:24 -08007463 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7464 // Creating a defensive copy to prevent the sender from modifying the list being
7465 // reflected in the return value of this method.
7466 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007467 return Collections.unmodifiableList(tempRequests);
7468 }
7469
James Mattisb1392002021-03-31 13:57:52 -07007470 void linkDeathRecipient() {
7471 if (null != mBinder) {
7472 try {
7473 mBinder.linkToDeath(this, 0);
7474 } catch (RemoteException e) {
7475 binderDied();
7476 }
7477 }
7478 }
7479
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007480 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007481 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007482 try {
7483 mBinder.unlinkToDeath(this, 0);
7484 } catch (NoSuchElementException e) {
7485 // Temporary workaround for b/194394697 pending analysis of additional logs
7486 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7487 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007488 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007489 }
7490
paulhu48291862021-07-14 14:53:57 +08007491 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7492 // Compare two preference orders.
7493 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007494 }
7495
paulhu48291862021-07-14 14:53:57 +08007496 int getPreferenceOrderForNetd() {
7497 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7498 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7499 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007500 }
paulhu48291862021-07-14 14:53:57 +08007501 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007502 }
7503
James Mattis4fce5d12020-11-12 15:53:42 -08007504 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007505 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007506 // As an immutable collection, mRequests cannot change by the time the
7507 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7508 // is acceptable. Use handleReleaseNetworkRequest and not directly
7509 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7510 // the app already unregistered the request.
7511 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7512 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007513 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007514
James Mattis4fce5d12020-11-12 15:53:42 -08007515 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007516 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007517 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7518 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007519 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007520 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007521 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007522 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007523 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007524 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007525 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007526 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007527 }
7528
Junyu Lai00d92df2022-07-05 11:01:52 +08007529 // Keep backward compatibility since the ServiceSpecificException is used by
7530 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7531 public static class RequestInfoPerUidCounter extends PerUidCounter {
7532 RequestInfoPerUidCounter(int maxCountPerUid) {
7533 super(maxCountPerUid);
7534 }
7535
7536 @Override
7537 public synchronized void incrementCountOrThrow(int uid) {
7538 try {
7539 super.incrementCountOrThrow(uid);
7540 } catch (IllegalStateException e) {
7541 throw new ServiceSpecificException(
7542 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7543 "Uid " + uid + " exceeded its allotted requests limit");
7544 }
7545 }
7546
7547 @Override
7548 public synchronized void decrementCountOrThrow(int uid) {
7549 throw new UnsupportedOperationException("Use decrementCount instead.");
7550 }
7551
7552 public synchronized void decrementCount(int uid) {
7553 try {
7554 super.decrementCountOrThrow(uid);
7555 } catch (IllegalStateException e) {
7556 logwtf("Exception when decrement per uid request count: ", e);
7557 }
7558 }
7559 }
7560
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007561 // This checks that the passed capabilities either do not request a
7562 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007563 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007564 int callerPid, int callerUid, String callerPackageName) {
Junyu Lai71b51532024-02-01 10:39:01 +08007565 if (null != nc.getSsid() && !hasSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007566 throw new SecurityException("Insufficient permissions to request a specific SSID");
7567 }
paulhu1a407652019-03-22 16:35:06 +08007568
7569 if (nc.hasSignalStrength()
Junyu Lai71b51532024-02-01 10:39:01 +08007570 && !hasNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
paulhu1a407652019-03-22 16:35:06 +08007571 throw new SecurityException(
7572 "Insufficient permissions to request a specific signal strength");
7573 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007574 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007575
Ying Xu7cabd322024-01-15 18:40:15 -08007576 if (nc.getSubscriptionIds().isEmpty()) {
7577 return;
Benedict Wong53de25f2021-03-24 14:01:51 -07007578 }
Ying Xu7cabd322024-01-15 18:40:15 -08007579 if (mRequestRestrictedWifiEnabled
7580 && canRequestRestrictedNetworkDueToCarrierPrivileges(nc, callerUid)) {
7581 return;
7582 }
7583 enforceNetworkFactoryPermission();
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007584 }
7585
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007586 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007587 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007588 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007589 // mNetworkRequests may contain the same value multiple times in case of
7590 // multilayer requests. It won't matter in this case because the thresholds
7591 // will then be the same and be deduplicated as they enter the `thresholds` set.
7592 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007593 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7594 for (final NetworkRequest req : nri.mRequests) {
7595 if (req.networkCapabilities.hasSignalStrength()
7596 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7597 thresholds.add(req.networkCapabilities.getSignalStrength());
7598 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007599 }
7600 }
7601 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007602 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007603 }
7604
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007605 private void updateSignalStrengthThresholds(
7606 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007607 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007608
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007609 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007610 String detail;
7611 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7612 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7613 } else {
7614 detail = reason;
7615 }
7616 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007617 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007618 }
7619
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007620 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007621 }
7622
Chalard Jeandd421992021-12-16 23:16:02 +09007623 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007624 if (nc == null) {
7625 return;
7626 }
7627 NetworkSpecifier ns = nc.getNetworkSpecifier();
7628 if (ns == null) {
7629 return;
7630 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007631 if (ns instanceof MatchAllNetworkSpecifier) {
7632 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7633 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007634 }
7635
Chalard Jeandd421992021-12-16 23:16:02 +09007636 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007637 ensureValidNetworkSpecifier(nc);
7638 if (nc.isPrivateDnsBroken()) {
7639 throw new IllegalArgumentException("Can't request broken private DNS");
7640 }
Chalard Jeande665262022-02-25 16:12:12 +09007641 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007642 throw new IllegalArgumentException("Can't request access UIDs");
7643 }
lucasline117e2e2019-10-22 18:27:33 +08007644 }
7645
Chalard Jeandd421992021-12-16 23:16:02 +09007646 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7647 ensureListenableCapabilities(nc);
7648 final String badCapability = nc.describeFirstNonRequestableCapability();
7649 if (badCapability != null) {
7650 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7651 }
7652 }
7653
Chiachang Wang3bc52762021-11-25 14:17:57 +08007654 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7655 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007656 private boolean isTargetSdkAtleast(int version, int callingUid,
7657 @NonNull String callingPackageName) {
7658 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007659 final PackageManager pm =
7660 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007661 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007662 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007663 if (callingVersion < version) return false;
7664 } catch (PackageManager.NameNotFoundException e) { }
7665 return true;
7666 }
7667
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007668 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007669 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007670 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007671 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007672 @Nullable String callingAttributionTag) {
Junyu Lai71b51532024-02-01 10:39:01 +08007673 if (legacyType != TYPE_NONE && !hasNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007674 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7675 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007676 throw new SecurityException("Insufficient permissions to specify legacy type");
7677 }
markchienfac84a22020-03-18 21:16:15 +08007678 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007679 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007680 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007681 // Privileged callers can track the default network of another UID by passing in a UID.
7682 if (asUid != Process.INVALID_UID) {
7683 enforceSettingsPermission();
7684 } else {
7685 asUid = callingUid;
7686 }
junyulaiad010792021-01-11 16:53:38 +08007687 final NetworkRequest.Type reqType;
7688 try {
7689 reqType = NetworkRequest.Type.values()[reqTypeInt];
7690 } catch (ArrayIndexOutOfBoundsException e) {
7691 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7692 }
7693 switch (reqType) {
7694 case TRACK_DEFAULT:
7695 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007696 // is unused and will be replaced by ones appropriate for the UID (usually, the
7697 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007698 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007699 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007700 enforceAccessPermission();
7701 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007702 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007703 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007704 networkCapabilities = new NetworkCapabilities(defaultNc);
7705 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007706 case BACKGROUND_REQUEST:
7707 enforceNetworkStackOrSettingsPermission();
7708 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007709 case REQUEST:
7710 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7711 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007712 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007713 // TODO: this is incorrect. We mark the request as metered or not depending on
7714 // the state of the app when the request is filed, but we never change the
7715 // request if the app changes network state. http://b/29964605
7716 enforceMeteredApnPolicy(networkCapabilities);
7717 break;
junyulai1b1c8742021-03-12 20:05:08 +08007718 case LISTEN_FOR_BEST:
7719 enforceAccessPermission();
7720 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7721 break;
junyulaiad010792021-01-11 16:53:38 +08007722 default:
7723 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007724 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007725 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007726 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007727 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007728
junyulai1b1c8742021-03-12 20:05:08 +08007729 // Enforce FOREGROUND if the caller does not have permission to use background network.
7730 if (reqType == LISTEN_FOR_BEST) {
7731 restrictBackgroundRequestForCaller(networkCapabilities);
7732 }
7733
7734 // Set the UID range for this request to the single UID of the requester, unless the
7735 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007736 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7737 // are no visible methods to set the UIDs, an app could use reflection to try and get
7738 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007739 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007740 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7741 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007742
Etan Cohen85000162017-02-05 10:42:27 -08007743 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007744 throw new IllegalArgumentException("Bad timeout specified");
7745 }
Etan Cohen9786d922015-11-18 10:56:15 -08007746
James Mattis3ce3d3c2021-02-09 18:18:28 -08007747 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007748 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007749 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007750 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007751 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007752 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007753
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007754 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7755 // copied from the default request above. (This is necessary to ensure, for example, that
7756 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7757 // changes don't alter request matching.
7758 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7759 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007760 throw new IllegalStateException(
7761 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007762 + networkCapabilities + " vs. " + defaultNc);
7763 }
7764
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007765 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007766 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007767 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007768 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007769 }
7770 return networkRequest;
7771 }
7772
James Mattis3ce3d3c2021-02-09 18:18:28 -08007773 /**
7774 * Return the nri to be used when registering a network request. Specifically, this is used with
7775 * requests registered to track the default request. If there is currently a per-app default
7776 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7777 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007778 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7779 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007780 * @param nr the network request for the nri.
7781 * @param msgr the messenger for the nri.
7782 * @param binder the binder for the nri.
7783 * @param callingAttributionTag the calling attribution tag for the nri.
7784 * @return the nri to register.
7785 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007786 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007787 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007788 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007789 @Nullable String callingAttributionTag) {
7790 final List<NetworkRequest> requests;
7791 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7792 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007793 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007794 } else {
7795 requests = Collections.singletonList(nr);
7796 }
Roshan Pius951c0032020-12-22 15:10:42 -08007797 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007798 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007799 }
7800
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007801 private boolean shouldCheckCapabilitiesDeclaration(
7802 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7803 @NonNull final String callingPackageName) {
7804 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7805 // Only run the check if the change is enabled.
7806 if (!mDeps.isChangeEnabled(
7807 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7808 callingPackageName, user)) {
7809 return false;
7810 }
7811
7812 return networkCapabilities.hasCapability(
7813 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7814 || networkCapabilities.hasCapability(
7815 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7816 }
7817
7818 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007819 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007820 // This check is added to fix the linter error for "current min is 30", which is not going
7821 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007822 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007823 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7824 return;
7825 }
7826 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007827 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007828 try {
7829 synchronized (mSelfCertifiedCapabilityCache) {
7830 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7831 callerPackageName);
7832 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007833 final PackageManager packageManager =
7834 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
7835 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007836 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7837 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7838 callerPackageName
7839 );
7840 final XmlResourceParser parser = packageManager
7841 .getResourcesForApplication(callerPackageName)
7842 .getXml(networkSliceProperty.getResourceId());
7843 applicationNetworkCapabilities =
7844 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7845 mSelfCertifiedCapabilityCache.put(callerPackageName,
7846 applicationNetworkCapabilities);
7847 }
7848
7849 }
7850 } catch (PackageManager.NameNotFoundException ne) {
7851 throw new SecurityException(
7852 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7853 + " property");
7854 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7855 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007856 } finally {
7857 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007858 }
7859
7860 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7861 networkCapabilities);
7862 }
Ying Xu7cabd322024-01-15 18:40:15 -08007863
7864 private boolean canRequestRestrictedNetworkDueToCarrierPrivileges(
7865 NetworkCapabilities networkCapabilities, int callingUid) {
7866 if (mRequestRestrictedWifiEnabled) {
7867 // For U+ devices, callers with carrier privilege could request restricted networks
7868 // with CBS capabilities, or any restricted WiFi networks.
7869 return ((networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7870 || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))
7871 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities));
7872 } else {
7873 // For T+ devices, callers with carrier privilege could request with CBS
7874 // capabilities.
7875 return (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7876 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities));
7877 }
7878 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007879 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007880 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007881 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7882 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007883 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
7884 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007885 }
Ying Xu7cabd322024-01-15 18:40:15 -08007886 if (!networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
7887 if (!canRequestRestrictedNetworkDueToCarrierPrivileges(
7888 networkCapabilities, callingUid)) {
7889 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007890 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007891 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007892 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007893 }
7894 }
7895
fenglu3f357402015-03-20 11:29:56 -07007896 @Override
fenglub00f4882015-04-21 17:12:05 -07007897 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007898 enforceAccessPermission();
7899 NetworkAgentInfo nai = null;
7900 if (network == null) {
7901 return false;
7902 }
7903 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007904 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007905 }
7906 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007907 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007908 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007909 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007910 Integer uidReqs = mBandwidthRequests.get(uid);
7911 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007912 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007913 }
7914 mBandwidthRequests.put(uid, ++uidReqs);
7915 }
fenglu3f357402015-03-20 11:29:56 -07007916 return true;
7917 }
7918 return false;
7919 }
7920
Felipe Leme0a5ae422016-06-20 16:36:29 -07007921 private boolean isSystem(int uid) {
7922 return uid < Process.FIRST_APPLICATION_UID;
7923 }
fenglu3f357402015-03-20 11:29:56 -07007924
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007925 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007926 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007927 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007928 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007929 return;
7930 }
Hugo Benichi39621362017-02-11 17:04:43 +09007931 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7932 // Policy already enforced.
7933 return;
7934 }
paulhuaf50d7d2020-12-24 19:47:34 +08007935 final long ident = Binder.clearCallingIdentity();
7936 try {
7937 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7938 // If UID is restricted, don't allow them to bring up metered APNs.
7939 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7940 }
7941 } finally {
7942 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007943 }
7944 }
7945
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007946 @Override
7947 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007948 PendingIntent operation, @NonNull String callingPackageName,
7949 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007950 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007951 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007952 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007953 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007954 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007955 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007956 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007957 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007958 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007959 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7960 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007961
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007962 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007963 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007964 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7965 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007966 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007967 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7968 nri));
7969 return networkRequest;
7970 }
7971
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007972 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7973 mHandler.sendMessageDelayed(
7974 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007975 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007976 }
7977
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007978 @Override
7979 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007980 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007981 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007982 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007983 }
7984
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007985 // In order to implement the compatibility measure for pre-M apps that call
7986 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7987 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7988 // This ensures it has permission to do so.
7989 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7990 if (nc == null) {
7991 return false;
7992 }
7993 int[] transportTypes = nc.getTransportTypes();
7994 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7995 return false;
7996 }
7997 try {
7998 mContext.enforceCallingOrSelfPermission(
7999 android.Manifest.permission.ACCESS_WIFI_STATE,
8000 "ConnectivityService");
8001 } catch (SecurityException e) {
8002 return false;
8003 }
8004 return true;
8005 }
8006
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008007 @Override
8008 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08008009 Messenger messenger, IBinder binder,
8010 @NetworkCallback.Flag int callbackFlags,
8011 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008012 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09008013 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
8014 enforceAccessPermission();
8015 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008016
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008017 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008018 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008019 Binder.getCallingPid(), callingUid, callingPackageName);
8020 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09008021 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
8022 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
8023 // onLost and onAvailable callbacks when networks move in and out of the background.
8024 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
8025 // can't request networks.
8026 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09008027 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07008028
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008029 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09008030 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08008031 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008032 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08008033 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09008034 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008035
8036 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
8037 return networkRequest;
8038 }
8039
8040 @Override
8041 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08008042 PendingIntent operation, @NonNull String callingPackageName,
8043 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00008044 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008045 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04008046 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
8047 enforceAccessPermission();
8048 }
Chalard Jeandd421992021-12-16 23:16:02 +09008049 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008050 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008051 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09008052 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08008053 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09008054
8055 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09008056 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008057 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
8058 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09008059 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04008060
WeiZhang1cc3f172021-06-03 19:02:04 -05008061 mHandler.sendMessage(mHandler.obtainMessage(
8062 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008063 }
8064
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008065 /** Returns the next Network provider ID. */
8066 public final int nextNetworkProviderId() {
8067 return mNextNetworkProviderId.getAndIncrement();
8068 }
8069
Erik Kline0c04b742016-07-07 16:50:58 +09008070 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008071 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09008072 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09008073 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09008074 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008075 }
8076
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008077 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
8078 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008079 // Avoid creating duplicates. even if an app makes a direct AIDL call.
8080 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
8081 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08008082 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008083 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008084 return;
8085 }
8086
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008087 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
8088 mNetworkProviderInfos.put(npi.messenger, npi);
8089 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008090 }
8091
8092 @Override
8093 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008094 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08008095 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008096 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08008097 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008098 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
8099 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008100 }
8101
8102 @Override
8103 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008104 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008105 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008106 }
8107
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008108 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09008109 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008110 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
8111 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09008112 Objects.requireNonNull(score);
8113 Objects.requireNonNull(caps);
8114 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008115 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008116 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09008117 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
8118 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008119 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
8120 }
8121
Chalard Jeanbb902a52021-08-18 01:35:19 +09008122 private void updateOfferScore(final NetworkOffer offer) {
8123 final boolean yieldToBadWiFi =
8124 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
8125 final NetworkOffer newOffer = new NetworkOffer(
8126 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
8127 offer.caps, offer.callback, offer.providerId);
8128 if (offer.equals(newOffer)) return;
8129 handleRegisterNetworkOffer(newOffer);
8130 }
8131
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008132 @Override
8133 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08008134 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008135 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
8136 }
8137
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008138 private void handleUnregisterNetworkProvider(Messenger messenger) {
8139 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
8140 if (npi == null) {
8141 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008142 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008143 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008144 // Unregister all the offers from this provider
8145 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
8146 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09008147 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008148 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
8149 toRemove.add(noi);
8150 }
8151 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09008152 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008153 handleUnregisterNetworkOffer(noi);
8154 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008155 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008156 }
8157
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008158 @Override
James Mattisf7027322020-12-13 16:28:14 -08008159 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008160 if (request.hasTransport(TRANSPORT_TEST)) {
8161 enforceNetworkFactoryOrTestNetworksPermission();
8162 } else {
8163 enforceNetworkFactoryPermission();
8164 }
James Mattisf7027322020-12-13 16:28:14 -08008165 final NetworkRequestInfo nri = mNetworkRequests.get(request);
8166 if (nri != null) {
8167 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
8168 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
8169 mHandler.post(() -> handleReleaseNetworkRequest(
8170 nri.mRequests.get(0), mDeps.getCallingUid(), true));
8171 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008172 }
8173
Paul Jensen1f567382015-02-13 14:18:39 -05008174 // NOTE: Accessed on multiple threads, must be synchronized on itself.
8175 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008176 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008177 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008178 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008179 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008180 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008181
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008182 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008183 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008184 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008185
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008186 // UID ranges for users that are currently blocked by VPNs.
8187 // This array is accessed and iterated on multiple threads without holding locks, so its
8188 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8189 // (on the handler thread).
8190 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8191
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008192 // Must only be accessed on the handler thread
8193 @NonNull
8194 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8195
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008196 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008197 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008198
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008199 // Current OEM network preferences. This object must only be written to on the handler thread.
8200 // Since it is immutable and always non-null, other threads may read it if they only care
8201 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008202 @NonNull
8203 private OemNetworkPreferences mOemNetworkPreferences =
8204 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008205 // Current per-profile network preferences. This object follows the same threading rules as
8206 // the OEM network preferences above.
8207 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008208 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8209 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008210
lucaslin3ba7cc22022-12-19 02:35:33 +00008211 // Current VPN network preferences. This object follows the same threading rules as the OEM
8212 // network preferences above.
8213 @NonNull
8214 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8215 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8216
paulhu51f77dc2021-06-07 02:34:20 +00008217 // A set of UIDs that should use mobile data preferentially if available. This object follows
8218 // the same threading rules as the OEM network preferences above.
8219 @NonNull
8220 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8221
James Mattiscb1e0362021-04-06 17:07:42 -07008222 // OemNetworkPreferences activity String log entries.
8223 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8224 @NonNull
8225 private final LocalLog mOemNetworkPreferencesLogs =
8226 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8227
James Mattis02220e22021-03-13 19:27:21 -08008228 /**
8229 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8230 * @param packageName the package name to check existence of a mapping for.
8231 * @return true if a mapping exists, false otherwise
8232 */
8233 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8234 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8235 }
8236
James Mattise3ef1912020-12-20 11:09:58 -08008237 // The always-on request for an Internet-capable network that apps without a specific default
8238 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008239 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008240 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008241 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008242 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008243 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008244 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008245 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008246
James Mattisd31bdfa2020-12-23 16:37:26 -08008247 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8248 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8249 }
8250
8251 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008252 * Return the default network request currently tracking the given uid.
8253 * @param uid the uid to check.
8254 * @return the NetworkRequestInfo tracking the given uid.
8255 */
8256 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008257 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008258 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008259 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008260 // Checking the first request is sufficient as only multilayer requests will have more
8261 // than one request and for multilayer, all requests will track the same uids.
8262 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008263 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008264 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008265 highestPriorityNri = nri;
8266 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008267 }
8268 }
paulhuaa0743d2021-05-26 21:56:03 +08008269 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008270 }
8271
8272 /**
8273 * Get a copy of the network requests of the default request that is currently tracking the
8274 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008275 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8276 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008277 * @param requestorUid the uid to check the default for.
8278 * @param requestorPackageName the requestor's package name.
8279 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8280 */
8281 @NonNull
8282 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008283 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008284 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008285 getDefaultRequestTrackingUid(asUid).mRequests,
8286 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008287 }
8288
8289 /**
8290 * Copy the given nri's NetworkRequest collection.
8291 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008292 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8293 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008294 * @param requestorUid the uid to set on the copied collection.
8295 * @param requestorPackageName the package name to set on the copied collection.
8296 * @return the copied NetworkRequest collection.
8297 */
8298 @NonNull
8299 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008300 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8301 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008302 final List<NetworkRequest> requests = new ArrayList<>();
8303 for (final NetworkRequest nr : requestsToCopy) {
8304 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008305 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008306 nr.legacyType, nextNetworkRequestId(), nr.type));
8307 }
8308 return requests;
8309 }
8310
8311 @NonNull
8312 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008313 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8314 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008315 // These capabilities are for a TRACK_DEFAULT callback, so:
8316 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8317 // mDefaultRequest and a per-UID default request.
8318 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008319 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008320 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008321 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8322 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008323 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008324 restrictRequestUidsForCallerAndSetRequestorInfo(
8325 netCap, requestorUid, requestorPackageName);
8326 return netCap;
8327 }
8328
8329 /**
8330 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8331 * @param nr the network request to check for equality against.
8332 * @return the nri if one exists, null otherwise.
8333 */
8334 @Nullable
8335 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8336 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8337 if (nri.getNetworkRequestForCallback().equals(nr)) {
8338 return nri;
8339 }
8340 }
8341 return null;
8342 }
8343
8344 /**
8345 * Check if an nri is currently being managed by per-app default networking.
8346 * @param nri the nri to check.
8347 * @return true if this nri is currently being managed by per-app default networking.
8348 */
8349 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8350 // nri.mRequests.get(0) is only different from the original request filed in
8351 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8352 // functionality therefore if these two don't match, it means this particular nri is
8353 // currently being managed by a per-app default.
8354 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8355 }
8356
8357 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008358 * Determine if an nri is a managed default request that disallows default networking.
8359 * @param nri the request to evaluate
8360 * @return true if device-default networking is disallowed
8361 */
8362 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8363 // Check if this nri is a managed default that supports the default network at its
8364 // lowest priority request.
8365 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8366 final NetworkCapabilities lowestPriorityNetCap =
8367 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8368 return isPerAppDefaultRequest(nri)
8369 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8370 lowestPriorityNetCap));
8371 }
8372
Erik Kline05f2b402015-04-30 12:58:40 +09008373 // Request used to optionally keep mobile data active even when higher
8374 // priority networks like Wi-Fi are active.
8375 private final NetworkRequest mDefaultMobileDataRequest;
8376
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008377 // Request used to optionally keep wifi data active even when higher
8378 // priority networks like ethernet are active.
8379 private final NetworkRequest mDefaultWifiRequest;
8380
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008381 // Request used to optionally keep vehicle internal network always active
8382 private final NetworkRequest mDefaultVehicleRequest;
8383
James Mattisd31bdfa2020-12-23 16:37:26 -08008384 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8385 // network with no service. This NAI should never be matched against, nor should any public API
8386 // ever return the associated network. For this reason, this NAI is not in the list of available
8387 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8388 // default requests that don't support using the device default network which will ultimately
8389 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8390 @VisibleForTesting
8391 final NetworkAgentInfo mNoServiceNetwork;
8392
Chalard Jean5b409c72021-02-04 13:12:59 +09008393 // The NetworkAgentInfo currently satisfying the default request, if any.
8394 private NetworkAgentInfo getDefaultNetwork() {
8395 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008396 }
8397
James Mattis2516da32021-01-31 17:06:19 -08008398 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008399 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008400 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8401 // Currently, all network requests will have the same uids therefore checking the first
8402 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008403 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008404 if (null == uids) {
8405 continue;
8406 }
8407 for (final UidRange range : uids) {
8408 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008409 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008410 highestPriorityNri = nri;
8411 }
James Mattis2516da32021-01-31 17:06:19 -08008412 }
8413 }
8414 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008415 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008416 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008417 }
8418
Varun Ananddf569952019-02-06 10:13:38 -08008419 @Nullable
8420 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8421 return nai != null ? nai.network : null;
8422 }
8423
8424 private void ensureRunningOnConnectivityServiceThread() {
8425 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8426 throw new IllegalStateException(
8427 "Not running on ConnectivityService thread: "
8428 + Thread.currentThread().getName());
8429 }
8430 }
8431
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008432 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008433 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8434 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008435 }
8436
Chalard Jean29d06db2018-05-02 21:14:54 +09008437 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008438 * Returns whether local agents are supported on this device.
8439 *
8440 * Local agents are supported from U on TVs, and from V on all devices.
8441 */
8442 @VisibleForTesting
8443 public boolean areLocalAgentsSupported() {
8444 final PackageManager pm = mContext.getPackageManager();
8445 // Local agents are supported starting on U on TVs and on V on everything else.
8446 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8447 }
8448
8449 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008450 * Register a new agent with ConnectivityService to handle a network.
8451 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008452 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008453 * @param networkInfo the initial info associated with this network. It can be updated later :
8454 * see {@link #updateNetworkInfo}.
8455 * @param linkProperties the initial link properties of this network. They can be updated
8456 * later : see {@link #updateLinkProperties}.
8457 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008458 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008459 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008460 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008461 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008462 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008463 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008464 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008465 public Network registerNetworkAgent(INetworkAgent na,
8466 NetworkInfo networkInfo,
8467 LinkProperties linkProperties,
8468 NetworkCapabilities networkCapabilities,
8469 @NonNull NetworkScore initialScore,
8470 @Nullable LocalNetworkConfig localNetworkConfig,
8471 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008472 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008473 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8474 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8475 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008476 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008477 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008478 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008479 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008480 } else {
8481 enforceNetworkFactoryPermission();
8482 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008483 final boolean hasLocalCap =
8484 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8485 if (hasLocalCap && !areLocalAgentsSupported()) {
8486 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8487 throw new IllegalArgumentException("Local agents are not supported in this version");
8488 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008489 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8490 if (hasLocalCap != hasLocalNetworkConfig) {
8491 throw new IllegalArgumentException(null != localNetworkConfig
8492 ? "Only local network agents can have a LocalNetworkConfig"
8493 : "Local network agents must have a LocalNetworkConfig"
8494 );
8495 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008496
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008497 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008498 final long token = Binder.clearCallingIdentity();
8499 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008500 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008501 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8502 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008503 } finally {
8504 Binder.restoreCallingIdentity(token);
8505 }
8506 }
8507
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008508 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008509 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008510 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8511 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008512 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008513
Chalard Jeandbc46952022-02-02 00:14:18 +09008514 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8515 // and mutate them at any time.
8516 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8517 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8518 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008519 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008520
Chalard Jean366c5252022-01-25 18:27:53 +09008521 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008522 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008523 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8524 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008525 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008526 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008527 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8528 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8529 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008530
Chalard Jeandbc46952022-02-02 00:14:18 +09008531 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008532 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008533 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008534 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008535 mDeps.getNetworkStack().makeNetworkMonitor(
8536 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008537 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8538 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008539 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008540 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008541 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008542 }
8543
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008544 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008545 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008546 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008547 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008548 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008549 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8550 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8551 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008552
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008553 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008554
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008555 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008556 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008557 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008558 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008559
8560 try {
8561 networkMonitor.start();
8562 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008563 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008564 }
Chalard Jean366c5252022-01-25 18:27:53 +09008565
Chalard Jean1e4c2182023-10-06 18:45:53 +09008566 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008567 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008568 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008569 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008570 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008571 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008572 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008573 }
8574
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008575 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8576 @NonNull public final NetworkOffer offer;
8577
8578 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8579 this.offer = offer;
8580 }
8581
8582 @Override
8583 public void binderDied() {
8584 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8585 }
8586 }
8587
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008588 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8589 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8590 if (npi.providerId == providerId) return true;
8591 }
8592 return false;
8593 }
8594
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008595 /**
8596 * Register or update a network offer.
8597 * @param newOffer The new offer. If the callback member is the same as an existing
8598 * offer, it is an update of that offer.
8599 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008600 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008601 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8602 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008603 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008604 // This may actually happen if a provider updates its score or registers and then
8605 // immediately unregisters. The offer would still be in the handler queue, but the
8606 // provider would have been removed.
8607 if (DBG) log("Received offer from an unregistered provider");
8608 return;
8609 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008610 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8611 if (null != existingOffer) {
8612 handleUnregisterNetworkOffer(existingOffer);
8613 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008614 if (DBG) {
8615 // handleUnregisterNetworkOffer has already logged the old offer
8616 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8617 }
8618 } else {
8619 if (DBG) {
8620 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8621 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008622 }
8623 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8624 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008625 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008626 } catch (RemoteException e) {
8627 noi.binderDied();
8628 return;
8629 }
8630 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008631 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008632 }
8633
8634 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8635 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008636 if (DBG) {
8637 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8638 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008639
8640 // If the provider removes the offer and dies immediately afterwards this
8641 // function may be called twice in a row, but the array will no longer contain
8642 // the offer.
8643 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008644 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008645 }
8646
8647 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8648 @NonNull final INetworkOfferCallback callback) {
8649 ensureRunningOnConnectivityServiceThread();
8650 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008651 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008652 }
8653 return null;
8654 }
8655
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008656 /**
8657 * Called when receiving LinkProperties directly from a NetworkAgent.
8658 * Stores into |nai| any data coming from the agent that might also be written to the network's
8659 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8660 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008661 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008662 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008663 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8664 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008665 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008666 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008667 }
8668
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008669 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008670 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008671 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008672
Lorenzo Colittid523d142020-04-01 20:16:30 +09008673 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8674 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8675 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008676 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008677
Suprabh Shukla1e312032023-01-24 03:36:37 -08008678 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008679
8680 // update filtering rules, need to happen after the interface update so netd knows about the
8681 // new interface (the interface name -> index map becomes initialized)
8682 updateVpnFiltering(newLp, oldLp, networkAgent);
8683
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008684 updateMtu(newLp, oldLp);
8685 // TODO - figure out what to do for clat
8686// for (LinkProperties lp : newLp.getStackedLinks()) {
8687// updateMtu(lp, null);
8688// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008689 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008690 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008691 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8692 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008693
Erik Klineb9888902016-04-05 13:30:49 +09008694 updateRoutes(newLp, oldLp, netId);
8695 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008696 // Make sure LinkProperties represents the latest private DNS status.
8697 // This does not need to be done before updateDnses because the
8698 // LinkProperties are not the source of the private DNS configuration.
8699 // updateDnses will fetch the private DNS configuration from DnsManager.
8700 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008701
Chalard Jean5b409c72021-02-04 13:12:59 +09008702 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008703 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008704 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008705 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008706 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008707
8708 updateWakeOnLan(newLp);
8709
Hai Shalome58bdc62021-01-11 18:45:34 -08008710 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8711 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8712 // does, it needs to be merged here.
8713 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8714 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008715
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008716 // TODO - move this check to cover the whole function
8717 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008718 synchronized (networkAgent) {
8719 networkAgent.linkProperties = newLp;
8720 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008721 // Start or stop DNS64 detection and 464xlat according to network state.
8722 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008723 // Notify NSS when relevant events happened. Currently, NSS only cares about
8724 // interface changed to update clat interfaces accounting.
8725 final boolean interfacesChanged = oldLp == null
8726 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8727 if (interfacesChanged) {
8728 notifyIfacesChangedForNetworkStats();
8729 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008730 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8731 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008732 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008733 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008734
8735 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008736 }
8737
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008738 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8739 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8740 }
8741
Hai Shalome58bdc62021-01-11 18:45:34 -08008742 /**
8743 * @param naData captive portal data from NetworkAgent
8744 * @param apiData captive portal data from capport API
8745 */
8746 @Nullable
8747 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8748 CaptivePortalData apiData) {
8749 if (naData == null || apiData == null) {
8750 return naData == null ? apiData : naData;
8751 }
8752 final CaptivePortalData.Builder captivePortalBuilder =
8753 new CaptivePortalData.Builder(naData);
8754
8755 if (apiData.isCaptive()) {
8756 captivePortalBuilder.setCaptive(true);
8757 }
8758 if (apiData.isSessionExtendable()) {
8759 captivePortalBuilder.setSessionExtendable(true);
8760 }
8761 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8762 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8763 // otherwise data would be inconsistent. Prefer the capport API info if present,
8764 // as it can generally be refreshed more often.
8765 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8766 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8767 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8768 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8769 // No source has time / bytes remaining information: surface the newest refresh time
8770 // for other fields
8771 captivePortalBuilder.setRefreshTime(
8772 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8773 }
8774
Hai Shalom7c6ab402021-02-04 19:34:06 -08008775 // Prioritize the user portal URL from the network agent if the source is authenticated.
8776 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8777 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8778 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8779 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008780 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008781 // Prioritize the venue information URL from the network agent if the source is
8782 // authenticated.
8783 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8784 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8785 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8786 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008787 }
8788 return captivePortalBuilder.build();
8789 }
8790
Suprabh Shukla53e16392023-04-26 18:47:36 -07008791 @VisibleForTesting
8792 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008793 // This needs to be kept in sync and backwards compatible with the decoding logic in
8794 // NetdEventListenerService, which is non-mainline code.
8795 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8796 }
8797
Suprabh Shukla75642282023-04-25 23:15:43 -07008798 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8799 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8800 return true;
8801 }
8802 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8803 return true;
8804 }
8805 return false;
8806 }
8807
Suprabh Shukla1e312032023-01-24 03:36:37 -08008808 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008809 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008810 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008811 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008812 return;
8813 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008814
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008815 // Mask/mark of zero will not detect anything interesting.
8816 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008817 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008818 return;
8819 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008820
Suprabh Shukla1e312032023-01-24 03:36:37 -08008821 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008822 try {
8823 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008824 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008825 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008826 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008827 }
8828 } catch (Exception e) {
8829 loge("Exception modifying wakeup packet monitoring: " + e);
8830 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008831 }
8832
Junyu Lai970963e2022-10-25 15:46:47 +08008833 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008834 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008835 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008836 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008837 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008838 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008839 for (final String iface : interfaceDiff.added) {
8840 try {
8841 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008842 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008843 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008844 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008845 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008846 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008847 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008848 }
Paul Jensenbff73492014-04-28 10:33:11 -04008849 }
8850 }
Chalard Jean9589e722019-11-19 19:03:53 +09008851 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008852 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008853 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008854 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008855 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008856 } catch (Exception e) {
8857 loge("Exception removing interface: " + e);
8858 }
8859 }
8860 }
8861
Paul Jensene0fd4a82014-08-06 15:51:33 -04008862 /**
8863 * Have netd update routes from oldLp to newLp.
8864 * @return true if routes changed between oldLp and newLp
8865 */
Junyu Lai970963e2022-10-25 15:46:47 +08008866 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8867 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008868 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008869 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8870 new CompareOrUpdateResult<>(
8871 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008872 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008873 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008874
8875 // add routes before removing old in case it helps with continuous connectivity
8876
Chalard Jean9dd11612018-06-04 16:52:49 +09008877 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008878 for (RouteInfo route : routeDiff.added) {
8879 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008880 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008881 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008882 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008883 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008884 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008885 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008886 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008887 }
8888 }
8889 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008890 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008891 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008892 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008893 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008894 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008895 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008896 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008897 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008898 }
8899 }
8900
8901 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008902 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008903 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008904 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008905 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008906 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008907 }
8908 }
Tyler Weare4314862019-12-05 14:55:30 -08008909
8910 for (RouteInfo route : routeDiff.updated) {
8911 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8912 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008913 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008914 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008915 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008916 }
8917 }
8918 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8919 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008920 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008921
Junyu Lai970963e2022-10-25 15:46:47 +08008922 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8923 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008924 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8925 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008926 }
Erik Klineb9888902016-04-05 13:30:49 +09008927
Erik Kline31b4a9e2018-01-11 21:07:29 +09008928 if (DBG) {
8929 final Collection<InetAddress> dnses = newLp.getDnsServers();
8930 log("Setting DNS servers for network " + netId + " to " + dnses);
8931 }
Erik Klineb9888902016-04-05 13:30:49 +09008932 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008933 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008934 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008935 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008936 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008937 }
Erik Kline54e35c02017-04-07 15:29:29 +09008938 }
8939
Junyu Lai970963e2022-10-25 15:46:47 +08008940 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8941 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008942 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8943 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008944 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8945 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008946
8947 if (!wasFiltering && !needsFiltering) {
8948 // Nothing to do.
8949 return;
8950 }
8951
8952 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8953 // Nothing changed.
8954 return;
8955 }
8956
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008957 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008958 if (ranges == null || ranges.isEmpty()) {
8959 return;
8960 }
8961
Qingxi Libb8da982020-01-17 17:54:27 -08008962 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008963 // TODO: this create a window of opportunity for apps to receive traffic between the time
8964 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008965 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008966 // old rules are being removed.
8967 if (wasFiltering) {
8968 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8969 }
8970 if (needsFiltering) {
8971 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8972 }
8973 }
8974
Valentin Iftime9fa35092019-09-24 13:32:13 +02008975 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008976 if (mWolSupportedInterfaces == null) {
8977 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008978 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008979 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008980 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8981 }
8982
Luke Huangb913c812018-08-24 20:33:16 +08008983 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008984 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008985 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008986 }
8987 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008988 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008989 }
Luke Huangb913c812018-08-24 20:33:16 +08008990 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008991 }
8992
Chalard Jean62edfd82019-12-02 18:39:29 +09008993 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8994 @NonNull final NetworkCapabilities newNc) {
8995 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8996 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008997 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008998 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008999 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08009000 } catch (RemoteException | ServiceSpecificException e) {
9001 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09009002 }
9003 }
9004 }
9005
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009006 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009007 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09009008 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009009 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08009010 underlyingNetworks = underlyingNetworksOrDefault(
9011 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09009012 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009013 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
9014 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009015 // metered if any underlying is metered, or originally declared metered by the agent.
9016 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009017 boolean roaming = false; // roaming if any underlying is roaming
9018 boolean congested = false; // congested if any underlying is congested
9019 boolean suspended = true; // suspended if all underlying are suspended
9020
9021 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08009022 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009023 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08009024 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009025 for (Network underlyingNetwork : underlyingNetworks) {
9026 final NetworkAgentInfo underlying =
9027 getNetworkAgentInfoForNetwork(underlyingNetwork);
9028 if (underlying == null) continue;
9029
9030 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
9031 hadUnderlyingNetworks = true;
9032 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09009033 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009034 }
9035
9036 // Merge capabilities of this underlying network. For bandwidth, assume the
9037 // worst case.
9038 downKbps = NetworkCapabilities.minBandwidth(downKbps,
9039 underlyingCaps.getLinkDownstreamBandwidthKbps());
9040 upKbps = NetworkCapabilities.minBandwidth(upKbps,
9041 underlyingCaps.getLinkUpstreamBandwidthKbps());
9042 // If this underlying network is metered, the VPN is metered (it may cost money
9043 // to send packets on this network).
9044 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
9045 // If this underlying network is roaming, the VPN is roaming (the billing structure
9046 // is different than the usual, local one).
9047 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9048 // If this underlying network is congested, the VPN is congested (the current
9049 // condition of the network affects the performance of this network).
9050 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
9051 // If this network is not suspended, the VPN is not suspended (the VPN
9052 // is able to transfer some data).
9053 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08009054 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009055 }
9056 }
9057 if (!hadUnderlyingNetworks) {
9058 // No idea what the underlying networks are; assume reasonable defaults
9059 metered = true;
9060 roaming = false;
9061 congested = false;
9062 suspended = false;
9063 }
9064
Chalard Jean1d420b32022-10-12 16:39:37 +09009065 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009066 newNc.setLinkDownstreamBandwidthKbps(downKbps);
9067 newNc.setLinkUpstreamBandwidthKbps(upKbps);
9068 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
9069 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
9070 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
9071 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08009072 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009073 }
9074
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009075 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009076 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
9077 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
9078 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04009079 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09009080 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009081 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09009082 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09009083 // Don't complain for VPNs since they're not driven by requests and there is no risk of
9084 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009085 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09009086 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09009087 if (nai.everConnected()
9088 && !nai.isVPN()
9089 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009090 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09009091 // does not cause any request (that is not a listen) currently matching that agent to
9092 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009093 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09009094 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009095 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09009096 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009097 }
9098
Paul Jensen53f08952015-06-16 14:27:36 -04009099 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009100 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09009101 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009102 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04009103 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009104 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04009105 }
Chalard Jean254bd162022-08-25 13:04:51 +09009106 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009107 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009108 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009109 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009110 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009111 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009112 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009113 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009114 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009115 }
Chalard Jean254bd162022-08-25 13:04:51 +09009116 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08009117 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9118 } else {
9119 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9120 }
lucasline117e2e2019-10-22 18:27:33 +08009121 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009122
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009123 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09009124 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
9125 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009126 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09009127 }
9128
Lorenzo Colittibd079452021-07-02 11:47:57 +09009129 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09009130 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09009131 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009132 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009133 }
9134
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009135 return newNc;
9136 }
9137
Lorenzo Colitti44840702021-01-11 22:27:57 +09009138 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
9139 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
9140 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9141 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9142 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9143 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9144 if (prevSuspended != suspended) {
9145 // TODO (b/73132094) : remove this call once the few users of onSuspended and
9146 // onResumed have been removed.
9147 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
9148 : ConnectivityManager.CALLBACK_RESUMED);
9149 }
9150 if (prevSuspended != suspended || prevRoaming != roaming) {
9151 // updateNetworkInfo will mix in the suspended info from the capabilities and
9152 // take appropriate action for the network having possibly changed state.
9153 updateNetworkInfo(nai, nai.networkInfo);
9154 }
9155 }
9156
Ying Xu0d06b942024-02-09 21:04:08 -08009157 private void handleUidCarrierPrivilegesLost(int uid, int subId) {
Ying Xu7cabd322024-01-15 18:40:15 -08009158 ensureRunningOnConnectivityServiceThread();
9159 // A NetworkRequest needs to be revoked when all the conditions are met
9160 // 1. It requests restricted network
9161 // 2. The requestor uid matches the uid with the callback
9162 // 3. The app doesn't have Carrier Privileges
9163 // 4. The app doesn't have permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS
9164 for (final NetworkRequest nr : mNetworkRequests.keySet()) {
9165 if ((nr.isRequest() || nr.isListen())
9166 && !nr.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
9167 && nr.getRequestorUid() == uid
Ying Xu0d06b942024-02-09 21:04:08 -08009168 && getSubscriptionIdFromNetworkCaps(nr.networkCapabilities) == subId
Ying Xu7cabd322024-01-15 18:40:15 -08009169 && !hasConnectivityRestrictedNetworksPermission(uid, true)) {
9170 declareNetworkRequestUnfulfillable(nr);
9171 }
9172 }
9173
9174 // A NetworkAgent's allowedUids may need to be updated if the app has lost
9175 // carrier config
9176 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Ying Xu0d06b942024-02-09 21:04:08 -08009177 if (nai.networkCapabilities.getAllowedUidsNoCopy().contains(uid)
9178 && getSubscriptionIdFromNetworkCaps(nai.networkCapabilities) == subId) {
Ying Xu7cabd322024-01-15 18:40:15 -08009179 final NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
9180 NetworkAgentInfo.restrictCapabilitiesFromNetworkAgent(
9181 nc,
9182 uid,
9183 false /* hasAutomotiveFeature (irrelevant) */,
9184 mDeps,
9185 mCarrierPrivilegeAuthenticator);
9186 updateCapabilities(nai.getScore(), nai, nc);
9187 }
9188 }
9189 }
9190
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009191 /**
9192 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
9193 *
9194 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
9195 * capabilities we manage and store in {@code nai}, such as validated status and captive
9196 * portal status)
9197 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
9198 * potentially triggers rematches.
9199 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
9200 * change.)
9201 *
9202 * @param oldScore score of the network before any of the changes that prompted us
9203 * to call this function.
9204 * @param nai the network having its capabilities updated.
9205 * @param nc the new network capabilities.
9206 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009207 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09009208 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009209 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009210 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009211 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9212 if (null != differences) {
9213 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9214 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009215 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009216 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009217
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009218 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009219 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009220 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009221
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009222 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009223 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9224 // the change we're processing can't affect any requests, it can only affect the listens
9225 // on this network. We might have been called by rematchNetworkAndRequests when a
9226 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009227 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009228 } else {
9229 // If the requestable capabilities have changed or the score changed, we can't have been
9230 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009231 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009232 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009233 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009234 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009235
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009236 final boolean oldMetered = prevNc.isMetered();
9237 final boolean newMetered = newNc.isMetered();
9238 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009239
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009240 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009241 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9242 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009243 }
junyulaif2c67e42018-08-07 19:50:45 +08009244
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009245 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9246 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009247
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009248 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009249 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009250 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009251 }
9252
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009253 // This network might have been underlying another network. Propagate its capabilities.
9254 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009255
Ken Chen5a35cf92023-10-07 07:54:22 +08009256 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009257 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009258 }
lucaslin53e8a262021-06-08 01:43:59 +08009259
9260 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009261 }
9262
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009263 /** Convenience method to update the capabilities for a given network. */
9264 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009265 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009266 }
9267
Yang Sun29037f62023-12-04 10:31:58 +08009268 private void maybeApplyMulticastRoutingConfig(@NonNull final NetworkAgentInfo nai,
9269 final LocalNetworkConfig oldConfig,
9270 final LocalNetworkConfig newConfig) {
9271 final MulticastRoutingConfig oldUpstreamConfig =
9272 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9273 oldConfig.getUpstreamMulticastRoutingConfig();
9274 final MulticastRoutingConfig oldDownstreamConfig =
9275 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9276 oldConfig.getDownstreamMulticastRoutingConfig();
9277 final MulticastRoutingConfig newUpstreamConfig =
9278 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9279 newConfig.getUpstreamMulticastRoutingConfig();
9280 final MulticastRoutingConfig newDownstreamConfig =
9281 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9282 newConfig.getDownstreamMulticastRoutingConfig();
9283
9284 if (oldUpstreamConfig.equals(newUpstreamConfig) &&
9285 oldDownstreamConfig.equals(newDownstreamConfig)) {
9286 return;
9287 }
9288
9289 final String downstreamNetworkName = nai.linkProperties.getInterfaceName();
9290 final LocalNetworkInfo lni = localNetworkInfoForNai(nai);
9291 final Network upstreamNetwork = lni.getUpstreamNetwork();
9292
9293 if (upstreamNetwork != null) {
9294 final String upstreamNetworkName =
9295 getLinkProperties(upstreamNetwork).getInterfaceName();
9296 applyMulticastRoutingConfig(downstreamNetworkName, upstreamNetworkName, newConfig);
9297 }
9298 }
9299
9300 private void applyMulticastRoutingConfig(@NonNull String localNetworkInterfaceName,
9301 @NonNull String upstreamNetworkInterfaceName,
9302 @NonNull final LocalNetworkConfig config) {
Yang Sunca537d52024-01-19 12:53:50 +08009303 if (mMulticastRoutingCoordinatorService == null) {
9304 if (config.getDownstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE ||
9305 config.getUpstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE) {
9306 loge("Multicast routing is not supported, failed to configure " + config
9307 + " for " + localNetworkInterfaceName + " to "
9308 + upstreamNetworkInterfaceName);
9309 }
9310 return;
9311 }
Yang Sun29037f62023-12-04 10:31:58 +08009312
9313 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9314 upstreamNetworkInterfaceName, config.getUpstreamMulticastRoutingConfig());
9315 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9316 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9317 config.getDownstreamMulticastRoutingConfig());
9318 }
9319
9320 private void disableMulticastRouting(@NonNull String localNetworkInterfaceName,
9321 @NonNull String upstreamNetworkInterfaceName) {
Yang Sunca537d52024-01-19 12:53:50 +08009322 if (mMulticastRoutingCoordinatorService == null) {
9323 return;
9324 }
Yang Sun29037f62023-12-04 10:31:58 +08009325
9326 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9327 upstreamNetworkInterfaceName, MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9328 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9329 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9330 MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9331 }
9332
Chalard Jean1e4c2182023-10-06 18:45:53 +09009333 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009334 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009335 @Nullable final LocalNetworkConfig oldConfig,
9336 @NonNull final LocalNetworkConfig newConfig) {
9337 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009338 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9339 return;
9340 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009341
Chalard Jean4fe23392023-10-17 23:02:27 +09009342 if (VDBG) {
9343 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9344 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009345 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
Chalard Jean1e4c2182023-10-06 18:45:53 +09009346 configBuilder.setUpstreamMulticastRoutingConfig(
9347 newConfig.getUpstreamMulticastRoutingConfig());
9348 configBuilder.setDownstreamMulticastRoutingConfig(
9349 newConfig.getDownstreamMulticastRoutingConfig());
9350
9351 final NetworkRequest oldRequest =
9352 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9353 final NetworkCapabilities oldCaps =
9354 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9355 final NetworkRequestInfo oldNri =
9356 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9357 final NetworkAgentInfo oldSatisfier =
9358 null == oldNri ? null : oldNri.getSatisfier();
9359 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9360 final NetworkCapabilities newCaps =
9361 (null == newRequest) ? null : newRequest.networkCapabilities;
9362 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9363 if (null != oldRequest && requestUpdated) {
9364 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9365 if (null == newRequest && null != oldSatisfier) {
9366 // If there is an old satisfier, but no new request, then remove the old upstream.
9367 removeLocalNetworkUpstream(nai, oldSatisfier);
9368 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009369 // When there is a new request, the rematch sees the new request and sends the
9370 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9371 // But here there is no new request, so the rematch won't see anything. Send
9372 // callbacks to apps now to tell them about the loss of upstream.
9373 notifyNetworkCallbacks(nai,
9374 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009375 return;
9376 }
9377 }
9378 if (null != newRequest && requestUpdated) {
9379 // File the new request if :
9380 // - it has changed (requestUpdated), or
9381 // - it's the first time this local info (null == oldConfig)
9382 // is updated and the request has not been filed yet.
9383 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9384 // upstream (the best) but never request it to be brought up.
9385 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9386 nextNetworkRequestId(), LISTEN_FOR_BEST);
9387 configBuilder.setUpstreamSelector(nr);
9388 final NetworkRequestInfo nri = new NetworkRequestInfo(
9389 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9390 0 /* callbackFlags */, null /* attributionTag */);
9391 if (null != oldSatisfier) {
9392 // Set the old satisfier in the new NRI so that the rematch will see any changes
9393 nri.setSatisfier(oldSatisfier, nr);
9394 }
9395 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009396 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9397 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9398 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009399 handleRegisterNetworkRequest(nri);
9400 } else {
9401 configBuilder.setUpstreamSelector(oldRequest);
9402 nai.localNetworkConfig = configBuilder.build();
9403 }
Yang Sun29037f62023-12-04 10:31:58 +08009404 maybeApplyMulticastRoutingConfig(nai, oldConfig, newConfig);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009405 }
9406
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009407 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009408 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009409 *
9410 * Ingress interface filtering enforces that all apps under the given network can only receive
9411 * packets from the network's interface (and loopback). This is important for VPNs because
9412 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9413 * non-VPN interfaces.
9414 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009415 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009416 * 1. the network is an app VPN (not legacy VPN)
9417 * 2. the VPN does not allow bypass
9418 * 3. the VPN is fully-routed
9419 * 4. the VPN interface is non-null
9420 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009421 * @see INetd#firewallAddUidInterfaceRules
9422 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009423 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009424 @Nullable
9425 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009426 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009427 if (nc == null || lp == null) return null;
9428 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009429 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009430 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009431 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009432 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009433 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009434 && !lp.hasExcludeRoute()) {
9435 return lp.getInterfaceName();
9436 }
9437 return null;
9438 }
9439
9440 /**
9441 * Returns whether we need to set interface filtering rule or not
9442 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009443 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009444 String isolationIface) {
9445 // Allow rules are always needed if VPN isolation is enabled.
9446 if (isolationIface != null) return true;
9447
9448 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9449 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9450 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009451 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009452 }
9453
Chiachang Wang28afaff2020-12-10 22:24:47 +08009454 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9455 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9456 int index = 0;
9457 for (UidRange range : ranges) {
9458 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9459 index++;
9460 }
9461 return stableRanges;
9462 }
9463
Chalard Jeane6c95272022-01-25 21:04:21 +09009464 private static UidRangeParcel[] intsToUidRangeStableParcels(
9465 final @NonNull ArraySet<Integer> uids) {
9466 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9467 int index = 0;
9468 for (int uid : uids) {
9469 stableRanges[index] = new UidRangeParcel(uid, uid);
9470 index++;
9471 }
9472 return stableRanges;
9473 }
9474
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009475 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9476 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9477 for (int i = 0; i < ranges.length; i++) {
9478 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9479 }
9480 return stableRanges;
9481 }
9482
Motomu Utsumi93a22182023-03-16 17:04:21 +09009483 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009484 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009485 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9486 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009487 if (mDeps.isAtLeastU()) {
9488 final Set<Integer> exemptUidSet = new ArraySet<>();
9489 for (final int uid: exemptUids) {
9490 exemptUidSet.add(uid);
9491 }
9492 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9493 } else {
9494 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9495 }
Ken Chen5e65a852020-12-24 12:59:10 +08009496 } catch (Exception e) {
9497 loge("Exception in socket destroy: ", e);
9498 }
9499 }
9500 }
9501
paulhuaa0743d2021-05-26 21:56:03 +08009502 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009503 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009504 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9505 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9506 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009507 exemptUids[0] = VPN_UID;
9508 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009509 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9510
Motomu Utsumi6345e462023-03-13 13:24:50 +09009511 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009512 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009513 try {
9514 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009515 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009516 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009517 } else {
paulhu0e79d952021-06-09 16:11:35 +08009518 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009519 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009520 }
9521 } catch (Exception e) {
9522 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9523 " on netId " + nai.network.netId + ". " + e);
9524 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009525 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009526 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009527 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009528
lucaslin53e8a262021-06-08 01:43:59 +08009529 private boolean isProxySetOnAnyDefaultNetwork() {
9530 ensureRunningOnConnectivityServiceThread();
9531 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9532 final NetworkAgentInfo nai = nri.getSatisfier();
9533 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9534 return true;
9535 }
9536 }
9537 return false;
9538 }
9539
9540 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9541 NetworkCapabilities newNc) {
9542 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9543 // the proxy might be changed since the default network satisfied by the apps might also
9544 // changed.
9545 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9546 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009547 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9548 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009549 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009550 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9551 mProxyTracker.sendProxyBroadcast();
9552 }
9553 }
9554
Chalard Jeane6c95272022-01-25 21:04:21 +09009555 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9556 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009557 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9558 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009559 if (null == prevRanges) prevRanges = new ArraySet<>();
9560 if (null == newRanges) newRanges = new ArraySet<>();
9561 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9562
9563 prevRanges.removeAll(newRanges);
9564 newRanges.removeAll(prevRangesCopy);
9565
9566 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009567 // When updating the VPN uid routing rules, add the new range first then remove the old
9568 // range. If old range were removed first, there would be a window between the old
9569 // range being removed and the new range being added, during which UIDs contained
9570 // in both ranges are not subject to any VPN routing rules. Adding new range before
9571 // removing old range works because, unlike the filtering rules below, it's possible to
9572 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009573 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9574 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9575 // [1-5] & [1-2],[4-5] == [3]
9576 // Then we can do:
9577 // maybeCloseSockets([3])
9578 // mNetd.networkAddUidRanges([1-2],[4-5])
9579 // mNetd.networkRemoveUidRanges([1-5])
9580 // maybeCloseSockets([3])
9581 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9582 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009583 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009584 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009585 }
9586 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009587 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009588 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009589 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9590 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009591 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9592 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009593 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009594 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009595 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9596 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9597 // were added first and then newRanges got removed later, there would be only one uid
9598 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9599 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9600 // Note that this is in contrast with the (more robust) update of VPN routing rules
9601 // above, where the addition of new ranges happens before the removal of old ranges.
9602 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9603 // to be removed will never overlap with the new range to be added.
9604 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009605 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9606 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009607 }
9608 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009609 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009610 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009611 } catch (Exception e) {
9612 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009613 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009614 }
9615 }
9616
Chalard Jeande665262022-02-25 16:12:12 +09009617 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009618 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9619 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009620 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9621 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009622 if (prevEmpty && newEmpty) return;
9623
9624 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009625 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009626 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009627 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009628
9629 if (prevUids.equals(newUids)) return;
9630
9631 // This implementation is very simple and vastly faster for sets of Integers than
9632 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9633 // a key computed from the value and has storage for that.
9634 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9635 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9636 toRemove.removeAll(newUids);
9637 toAdd.removeAll(prevUids);
Chalard Jeane6c95272022-01-25 21:04:21 +09009638 try {
9639 if (!toAdd.isEmpty()) {
9640 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9641 nai.network.netId,
9642 intsToUidRangeStableParcels(toAdd),
9643 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9644 }
9645 if (!toRemove.isEmpty()) {
9646 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9647 nai.network.netId,
9648 intsToUidRangeStableParcels(toRemove),
9649 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9650 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009651 } catch (ServiceSpecificException e) {
9652 // Has the interface disappeared since the network was built ?
9653 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009654 } catch (RemoteException e) {
9655 // Netd died. This usually causes a runtime restart anyway.
9656 }
9657 }
9658
Junyu Lai2ed7d412022-10-07 16:52:21 +08009659 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9660 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009661 ensureRunningOnConnectivityServiceThread();
9662
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009663 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009664 // Ignore updates for disconnected networks
9665 return;
9666 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009667 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009668 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009669 + "; created=" + nai.getCreatedTime()
9670 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009671 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009672 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9673 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009674 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009675 }
9676
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009677 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9678 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009679 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009680 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009681 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009682 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9683 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9684 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009685 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9686 // need to be sent as a separate extra.
9687 final NetworkRequest req = nri.isMultilayerRequest()
9688 ? nri.getActiveRequest()
9689 // Non-multilayer listen requests do not have an active request
9690 : nri.mRequests.get(0);
9691 if (req == null) {
9692 Log.wtf(TAG, "No request in NRI " + nri);
9693 }
9694 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009695 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009696 sendIntent(nri.mPendingIntent, intent);
9697 }
9698 // else not handled
9699 }
9700
Michael Groover73f69482023-01-27 11:01:25 -06009701 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9702 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009703 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9704 mPendingIntentWakeLock.acquire();
9705 try {
9706 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009707 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009708 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009709 // Explicitly disallow the receiver from starting activities, to prevent apps from
9710 // utilizing the PendingIntent as a backdoor to do this.
9711 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9712 }
9713 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9714 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009715 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009716 } catch (PendingIntent.CanceledException e) {
9717 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9718 mPendingIntentWakeLock.release();
9719 releasePendingNetworkRequest(pendingIntent);
9720 }
9721 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9722 }
9723
9724 @Override
9725 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9726 String resultData, Bundle resultExtras) {
9727 if (DBG) log("Finished sending " + pendingIntent);
9728 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009729 // Release with a delay so the receiving client has an opportunity to put in its
9730 // own request.
9731 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009732 }
9733
Chalard Jean22350c92023-10-07 19:21:45 +09009734 @Nullable
9735 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9736 if (!nai.isLocalNetwork()) return null;
9737 final Network upstream;
9738 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9739 if (null == selector) {
9740 upstream = null;
9741 } else {
9742 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9743 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9744 upstream = (null == satisfier) ? null : satisfier.network;
9745 }
9746 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9747 }
9748
Chalard Jean46bfbf02022-02-02 00:56:25 +09009749 // networkAgent is only allowed to be null if notificationType is
9750 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9751 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009752 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009753 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009754 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009755 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009756 // Default request has no msgr. Also prevents callbacks from being invoked for
9757 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9758 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9759 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009760 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009761 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009762 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009763 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009764 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009765 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009766 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009767 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9768 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009769 }
Roshan Pius951c0032020-12-22 15:10:42 -08009770 final boolean includeLocationSensitiveInfo =
9771 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009772 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009773 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009774 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009775 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009776 networkCapabilitiesRestrictedForCallerPermissions(
9777 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9778 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009779 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009780 nri.mCallingAttributionTag);
9781 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009782 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9783 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009784 // The local network info is often null, so can't use the static putParcelable
9785 // method here.
9786 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9787 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009788 // For this notification, arg1 contains the blocked status.
9789 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009790 break;
9791 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009792 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009793 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009794 break;
9795 }
9796 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009797 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009798 final NetworkCapabilities netCap =
9799 networkCapabilitiesRestrictedForCallerPermissions(
9800 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9801 putParcelable(
9802 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009803 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009804 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009805 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009806 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009807 break;
9808 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009809 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009810 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9811 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009812 break;
9813 }
junyulaif2c67e42018-08-07 19:50:45 +08009814 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009815 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009816 msg.arg1 = arg1;
9817 break;
9818 }
Chalard Jean22350c92023-10-07 19:21:45 +09009819 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9820 if (!networkAgent.isLocalNetwork()) {
9821 Log.wtf(TAG, "Callback for local info for a non-local network");
9822 return;
9823 }
9824 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9825 break;
9826 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009827 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009828 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009829 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009830 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009831 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009832 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009833 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009834 }
James Mattis45d81842021-01-10 14:24:24 -08009835 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009836 } catch (RemoteException e) {
9837 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009838 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009839 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009840 }
9841
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009842 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9843 bundle.putParcelable(t.getClass().getSimpleName(), t);
9844 }
9845
Chalard Jean0702f982021-09-16 21:50:07 +09009846 /**
9847 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9848 *
9849 * When a request should be assigned to a new network, it is normally lingered to give
9850 * time for apps to gracefully migrate their connections. When both networks are on the same
9851 * radio, but that radio can't do time-sharing efficiently, this may end up being
9852 * counter-productive because any traffic on the old network may drastically reduce the
9853 * performance of the new network.
9854 * The stack supports a configuration to let modem vendors state that their radio can't
9855 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9856 * from one cell network to another can't be done gracefully.
9857 *
9858 * @param oldNai the old network serving the request
9859 * @param newNai the new network serving the request
9860 * @return whether the switch can be graceful
9861 */
9862 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9863 @NonNull final NetworkAgentInfo newSatisfier) {
9864 if (mCellularRadioTimesharingCapable) return true;
9865 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9866 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9867 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9868 }
9869
Paul Jensenaf94b982014-09-30 15:37:41 -04009870 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009871 if (nai.numRequestNetworkRequests() != 0) {
9872 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9873 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009874 // Ignore listening and track default requests.
9875 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009876 loge("Dead network still had at least " + nr);
9877 break;
9878 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009879 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009880 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009881 }
9882
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009883 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9884 if (oldNetwork == null) {
9885 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9886 return;
9887 }
Chalard Jean49707572019-12-10 21:07:02 +09009888 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009889
9890 // If we get here it means that the last linger timeout for this network expired. So there
9891 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009892 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009893
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009894 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009895 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009896 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009897 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009898 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009899 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009900 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009901 }
9902
James Mattise3ef1912020-12-20 11:09:58 -08009903 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9904 boolean isDefaultChanged = false;
9905 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9906 final NetworkReassignment.RequestReassignment reassignment =
9907 changes.getReassignment(defaultRequestInfo);
9908 if (null == reassignment) {
9909 continue;
9910 }
9911 // reassignment only contains those instances where the satisfying network changed.
9912 isDefaultChanged = true;
9913 // Notify system services of the new default.
9914 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9915 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009916
James Mattise3ef1912020-12-20 11:09:58 -08009917 if (isDefaultChanged) {
9918 // Hold a wakelock for a short time to help apps in migrating to a new default.
9919 scheduleReleaseNetworkTransitionWakelock();
9920 }
9921 }
9922
Aaron Huang9fe47be2021-06-08 13:11:45 +08009923 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9924 if (null == oldDefaultNetwork) return;
9925 // The network stopped being the default. If it was using a PAC proxy, then the
9926 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9927 // to the local proxy server, which would forward them over the newly default network.
9928 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9929 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9930 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9931 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9932 }
9933
James Mattise3ef1912020-12-20 11:09:58 -08009934 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9935 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9936 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9937 if (DBG) {
9938 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9939 }
Chalard Jean8e382112019-12-03 20:45:30 +09009940
James Mattisd31bdfa2020-12-23 16:37:26 -08009941 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9942 if (newDefaultNetwork != null) {
9943 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009944 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009945
James Mattisd31bdfa2020-12-23 16:37:26 -08009946 // Set an app level managed default and return since further processing only applies to the
9947 // default network.
9948 if (mDefaultRequest != nri) {
9949 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9950 return;
9951 }
9952
9953 makeDefaultNetwork(newDefaultNetwork);
9954
James Mattise3ef1912020-12-20 11:09:58 -08009955 if (oldDefaultNetwork != null) {
9956 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9957 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009958 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009959 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009960 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009961 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009962 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009963 updateTcpBufferSizes(null != newDefaultNetwork
9964 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009965 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009966 }
9967
James Mattisd31bdfa2020-12-23 16:37:26 -08009968 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9969 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9970 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9971 try {
9972 if (VDBG) {
9973 log("Setting default network for " + nri
9974 + " using UIDs " + nri.getUids()
9975 + " with old network " + (oldDefaultNetwork != null
9976 ? oldDefaultNetwork.network().getNetId() : "null")
9977 + " and new network " + (newDefaultNetwork != null
9978 ? newDefaultNetwork.network().getNetId() : "null"));
9979 }
9980 if (nri.getUids().isEmpty()) {
9981 throw new IllegalStateException("makeDefaultForApps called without specifying"
9982 + " any applications to set as the default." + nri);
9983 }
9984 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009985 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009986 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009987 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009988 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009989 }
9990 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009991 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009992 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009993 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009994 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009995 }
9996 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009997 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009998 }
9999 }
10000
Junyu Lai35665cc2022-12-19 17:37:48 +080010001 /**
10002 * Collect restricted uid ranges for the given network and UserHandle, these uids
10003 * are not restricted for matched enterprise networks but being restricted for non-matched
10004 * enterprise networks and non-enterprise networks.
10005 */
10006 @NonNull
10007 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
10008 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
10009 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
10010 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
10011 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
10012
10013 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
10014 // The NC is built from a `ProfileNetworkPreference` which has only one
10015 // enterprise ID, so it's guaranteed to have exactly one.
10016 final int prefId = pref.capabilities.getEnterpriseIds()[0];
10017 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
10018 continue;
10019 }
10020 }
10021
10022 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
10023 pref.capabilities.getUidRanges())) {
10024 throw new IllegalArgumentException(
10025 "Overlapping uid range in preference: " + pref);
10026 }
10027 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
10028 }
10029 return restrictedUidRanges;
10030 }
10031
10032 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +080010033 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +090010034 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +080010035
Junyu Lai35665cc2022-12-19 17:37:48 +080010036 ensureRunningOnConnectivityServiceThread();
10037 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
10038 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
10039 .getUserHandles(true /* excludeDying */);
10040 if (users.isEmpty()) {
10041 throw new IllegalStateException("No user is available");
10042 }
10043
10044 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10045 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
10046 for (final UserHandle user : users) {
10047 final ArraySet<UidRange> restrictedUidRanges =
10048 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
10049 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
10050 UidRange.createForUser(user), restrictedUidRanges));
10051 }
10052
10053 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
10054 configs.add(new NativeUidRangeConfig(
10055 nai.network.netId, rangesParcel, 0 /* subPriority */));
10056 }
10057
10058 // The netd API replaces the previous configs with the current configs.
10059 // Thus, for network disconnection or preference removal, no need to
10060 // unset previous config. Instead, collecting all currently needed
10061 // configs and issue to netd.
10062 try {
10063 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
10064 } catch (ServiceSpecificException e) {
10065 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +080010066 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +080010067 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +080010068 // Netd died. This will cause a runtime restart anyway.
10069 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +080010070 }
10071 }
10072
James Mattisd31bdfa2020-12-23 16:37:26 -080010073 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
10074 try {
10075 if (null != newDefaultNetwork) {
10076 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
10077 } else {
10078 mNetd.networkClearDefault();
10079 }
10080 } catch (RemoteException | ServiceSpecificException e) {
10081 loge("Exception setting default network :" + e);
10082 }
10083 }
10084
Chalard Jean05cbe972019-12-09 11:50:38 +090010085 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010086 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +090010087 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +090010088 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +090010089 processNewlySatisfiedListenRequests(nai);
10090 }
10091
10092 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -080010093 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10094 if (nri.isMultilayerRequest()) {
10095 continue;
10096 }
10097 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010098 if (!nr.isListen()) continue;
10099 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -080010100 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010101 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
10102 }
10103 }
Chalard Jeancd397a22019-11-22 22:33:33 +090010104 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010105
Chalard Jeancd397a22019-11-22 22:33:33 +090010106 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -080010107 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10108 if (nri.isMultilayerRequest()) {
10109 continue;
10110 }
10111 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010112 if (!nr.isListen()) continue;
10113 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
10114 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +090010115 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010116 }
10117 }
10118 }
10119
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010120 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010121 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010122 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -080010123 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +090010124 @Nullable public final NetworkRequest mOldNetworkRequest;
10125 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010126 @Nullable public final NetworkAgentInfo mOldNetwork;
10127 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -080010128 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010129 @Nullable final NetworkRequest oldNetworkRequest,
10130 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010131 @Nullable final NetworkAgentInfo oldNetwork,
10132 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010133 mNetworkRequestInfo = networkRequestInfo;
10134 mOldNetworkRequest = oldNetworkRequest;
10135 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010136 mOldNetwork = oldNetwork;
10137 mNewNetwork = newNetwork;
10138 }
Chalard Jean49707572019-12-10 21:07:02 +090010139
10140 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +090010141 final NetworkRequest requestToShow = null != mNewNetworkRequest
10142 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
10143 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -080010144 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
10145 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +090010146 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010147 }
10148
Chalard Jean46a62372019-12-10 21:25:24 +090010149 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010150
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010151 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +090010152 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010153 }
10154
10155 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +090010156 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +090010157 // The code is never supposed to add two reassignments of the same request. Make
10158 // sure this stays true, but without imposing this expensive check on all
10159 // reassignments on all user devices.
10160 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -080010161 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +090010162 throw new IllegalStateException("Trying to reassign ["
10163 + reassignment + "] but already have ["
10164 + existing + "]");
10165 }
10166 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +090010167 }
Chalard Jean46a62372019-12-10 21:25:24 +090010168 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010169 }
10170
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010171 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +090010172 // the passed request.
10173 @Nullable
10174 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010175 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010176 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010177 }
10178 return null;
10179 }
Chalard Jean49707572019-12-10 21:07:02 +090010180
10181 public String toString() {
10182 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
10183 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +090010184 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010185 for (final RequestReassignment rr : getRequestReassignments()) {
10186 sj.add(rr.toString());
10187 }
10188 return sj.toString();
10189 }
10190
10191 public String debugString() {
10192 final StringBuilder sb = new StringBuilder();
10193 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +090010194 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010195 for (final RequestReassignment rr : getRequestReassignments()) {
10196 sb.append("\n ").append(rr);
10197 }
10198 return sb.append("\n").toString();
10199 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010200 }
10201
Chalard Jean24344d72019-12-04 13:32:31 +090010202 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010203 @Nullable final NetworkRequest previousRequest,
10204 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +090010205 @Nullable final NetworkAgentInfo previousSatisfier,
10206 @Nullable final NetworkAgentInfo newSatisfier,
10207 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -080010208 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +090010209 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +090010210 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010211 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010212 log(" accepting network in place of " + previousSatisfier.toShortString()
10213 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010214 }
James Mattisa076c532020-12-02 14:12:41 -080010215 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010216 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +090010217 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +090010218 // If this network switch can't be supported gracefully, the request is not
10219 // lingered. This allows letting go of the network sooner to reclaim some
10220 // performance on the new network, since the radio can't do both at the same
10221 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010222 //
10223 // Also don't linger the request if the old network has been destroyed.
10224 // A destroyed network does not provide actual network connectivity, so
10225 // lingering it is not useful. In particular this ensures that a destroyed
10226 // network is outscored by its replacement,
10227 // then it is torn down immediately instead of being lingered, and any apps that
10228 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +090010229 previousSatisfier.lingerRequest(previousRequest.requestId, now);
10230 }
Chalard Jean24344d72019-12-04 13:32:31 +090010231 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010232 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010233 }
junyulai0ac374f2020-12-14 18:41:52 +080010234
10235 // To prevent constantly CPU wake up for nascent timer, if a network comes up
10236 // and immediately satisfies a request then remove the timer. This will happen for
10237 // all networks except in the case of an underlying network for a VCN.
10238 if (newSatisfier.isNascent()) {
10239 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +080010240 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010241 }
10242
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010243 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -080010244 newSatisfier.unlingerRequest(newRequest.requestId);
10245 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +080010246 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -080010247 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010248 }
Chalard Jeana8ac2302021-03-01 22:16:08 +090010249 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010250 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010251 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -080010252 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010253 }
James Mattisa076c532020-12-02 14:12:41 -080010254 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010255 }
James Mattisa076c532020-12-02 14:12:41 -080010256 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010257 }
10258
James Mattisa076c532020-12-02 14:12:41 -080010259 /**
10260 * This function is triggered when something can affect what network should satisfy what
10261 * request, and it computes the network reassignment from the passed collection of requests to
10262 * network match to the one that the system should now have. That data is encoded in an
10263 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
10264 * satisfier.
10265 *
10266 * After the reassignment is computed, it is applied to the state objects.
10267 *
10268 * @param networkRequests the nri objects to evaluate for possible network reassignment
10269 * @return NetworkReassignment listing of proposed network assignment changes
10270 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010271 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080010272 private NetworkReassignment computeNetworkReassignment(
10273 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010274 final NetworkReassignment changes = new NetworkReassignment();
10275
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010276 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010277 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010278 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010279 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010280 }
Chalard Jean857a1712019-12-10 21:08:07 +090010281
James Mattisa076c532020-12-02 14:12:41 -080010282 for (final NetworkRequestInfo nri : networkRequests) {
10283 // Non-multilayer listen requests can be ignored.
10284 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10285 continue;
10286 }
10287 NetworkAgentInfo bestNetwork = null;
10288 NetworkRequest bestRequest = null;
10289 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010290 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010291 // Stop evaluating as the highest possible priority request is satisfied.
10292 if (null != bestNetwork) {
10293 bestRequest = req;
10294 break;
10295 }
10296 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010297 if (null == bestNetwork && isDefaultBlocked(nri)) {
10298 // Remove default networking if disallowed for managed default requests.
10299 bestNetwork = mNoServiceNetwork;
10300 }
10301 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010302 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010303 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010304 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010305 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010306 }
10307 return changes;
10308 }
10309
James Mattisa076c532020-12-02 14:12:41 -080010310 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10311 return new HashSet<>(mNetworkRequests.values());
10312 }
10313
Paul Jensenc88b39b2015-06-16 14:27:36 -040010314 /**
James Mattisa076c532020-12-02 14:12:41 -080010315 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010316 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010317 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010318 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010319 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10320 }
10321
10322 /**
10323 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10324 * being disconnected.
10325 */
10326 private void rematchNetworksAndRequests(
10327 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10328 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010329 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010330 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010331 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010332 final long computed = SystemClock.elapsedRealtime();
10333 applyNetworkReassignment(changes, start);
10334 final long applied = SystemClock.elapsedRealtime();
10335 issueNetworkNeeds();
10336 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010337 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010338 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10339 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010340 log(changes.debugString());
10341 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010342 // Shorter form, only one line of log
10343 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10344 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010345 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010346 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010347
Chalard Jean1e4c2182023-10-06 18:45:53 +090010348 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10349 @Nullable final NetworkAgentInfo nai2) {
10350 if (null == nai1) return null == nai2;
10351 if (null == nai2) return false;
10352 return nai1.linkProperties.getInterfaceName()
10353 .equals(nai2.linkProperties.getInterfaceName());
10354 }
10355
Chalard Jeand7f762d2019-12-10 19:01:29 +090010356 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010357 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010358 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010359
10360 // Since most of the time there are only 0 or 1 background networks, it would probably
10361 // be more efficient to just use an ArrayList here. TODO : measure performance
10362 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10363 for (final NetworkAgentInfo nai : nais) {
10364 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10365 }
10366
Chalard Jeand7f762d2019-12-10 19:01:29 +090010367 // First, update the lists of satisfied requests in the network agents. This is necessary
10368 // because some code later depends on this state to be correct, most prominently computing
10369 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010370 for (final NetworkReassignment.RequestReassignment event :
10371 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010372 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10373 event.mOldNetworkRequest, event.mNewNetworkRequest,
10374 event.mOldNetwork, event.mNewNetwork,
10375 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010376 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010377
James Mattise3ef1912020-12-20 11:09:58 -080010378 // Process default network changes if applicable.
10379 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010380
Chalard Jean68eab722023-11-16 17:00:04 +090010381 // Update forwarding rules for the upstreams of local networks. Do this before sending
10382 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10383 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10384 // onAvailable so clients know what network the change is about. Store such changes in
10385 // an array that's only allocated if necessary (because it's almost never necessary).
10386 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10387 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10388 if (!nai.isLocalNetwork()) continue;
10389 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10390 if (null == nr) continue; // No upstream for this local network
10391 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10392 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10393 if (null == change) continue; // No change in upstreams for this network
10394 final String fromIface = nai.linkProperties.getInterfaceName();
10395 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10396 || change.mOldNetwork.isDestroyed()) {
10397 // There can be a change with the same interface name if the new network is the
10398 // replacement for the old network that was unregisteredAfterReplacement.
10399 try {
10400 if (null != change.mOldNetwork) {
10401 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10402 change.mOldNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010403 disableMulticastRouting(fromIface,
10404 change.mOldNetwork.linkProperties.getInterfaceName());
Chalard Jean68eab722023-11-16 17:00:04 +090010405 }
10406 // If the new upstream is already destroyed, there is no point in setting up
10407 // a forward (in fact, it might forward to the interface for some new network !)
10408 // Later when the upstream disconnects CS will try to remove the forward, which
10409 // is ignored with a benign log by RoutingCoordinatorService.
10410 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10411 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10412 change.mNewNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010413 applyMulticastRoutingConfig(fromIface,
10414 change.mNewNetwork.linkProperties.getInterfaceName(),
10415 nai.localNetworkConfig);
Chalard Jean68eab722023-11-16 17:00:04 +090010416 }
10417 } catch (final RemoteException e) {
10418 loge("Can't update forwarding rules", e);
10419 }
10420 }
10421 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10422 localInfoChangedAgents.add(nai);
10423 }
10424
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010425 // Notify requested networks are available after the default net is switched, but
10426 // before LegacyTypeTracker sends legacy broadcasts
10427 for (final NetworkReassignment.RequestReassignment event :
10428 changes.getRequestReassignments()) {
10429 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010430 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010431 } else {
James Mattisa076c532020-12-02 14:12:41 -080010432 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010433 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010434 }
10435 }
10436
junyulai0ac374f2020-12-14 18:41:52 +080010437 // Update the inactivity state before processing listen callbacks, because the background
10438 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010439 // just yet though, because they have to be sent after the listens are processed to keep
10440 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010441 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010442 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010443 // Rematching may have altered the inactivity state of some networks, so update all
10444 // inactivity timers. updateInactivityState reads the state from the network agent
10445 // and does nothing if the state has not changed : the source of truth is controlled
10446 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10447 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010448 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010449 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010450 }
10451 }
10452
Chalard Jeanb10ab412019-12-11 14:12:30 +090010453 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010454 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010455 // Process listen requests and update capabilities if the background state has
10456 // changed for this network. For consistency with previous behavior, send onLost
10457 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010458 processNewlyLostListenRequests(nai);
10459 if (oldBackground != nai.isBackgroundNetwork()) {
10460 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010461 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010462 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010463 }
10464
junyulai0ac374f2020-12-14 18:41:52 +080010465 for (final NetworkAgentInfo nai : inactiveNetworks) {
10466 // For nascent networks, if connecting with no foreground request, skip broadcasting
10467 // LOSING for backward compatibility. This is typical when mobile data connected while
10468 // wifi connected with mobile data always-on enabled.
10469 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010470 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010471 }
10472
Chalard Jean68eab722023-11-16 17:00:04 +090010473 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10474 if (null != localInfoChangedAgents) {
10475 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10476 notifyNetworkCallbacks(nai,
10477 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010478 }
10479 }
10480
James Mattise3ef1912020-12-20 11:09:58 -080010481 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010482
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010483 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010484 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010485 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010486 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010487 // This network has active linger timers and no requests, but is not
10488 // lingering. Linger it.
10489 //
10490 // One way (the only way?) this can happen if this network is unvalidated
10491 // and became unneeded due to another network improving its score to the
10492 // point where this network will no longer be able to satisfy any requests
10493 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010494 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010495 notifyNetworkLosing(nai, now);
10496 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010497 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010498 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010499 teardownUnneededNetwork(nai);
10500 }
10501 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010502 }
10503 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010504
Chalard Jean62edfd82019-12-02 18:39:29 +090010505 /**
10506 * Apply a change in background state resulting from rematching networks with requests.
10507 *
10508 * During rematch, a network may change background states by starting to satisfy or stopping
10509 * to satisfy a foreground request. Listens don't count for this. When a network changes
10510 * background states, its capabilities need to be updated and callbacks fired for the
10511 * capability change.
10512 *
10513 * @param nai The network that changed background states
10514 */
10515 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10516 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10517 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10518 updateNetworkPermissions(nai, newNc);
10519 nai.getAndSetNetworkCapabilities(newNc);
10520 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10521 }
10522
Chalard Jeanf0344532019-11-19 19:23:38 +090010523 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010524 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010525 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010526 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10527 changes.getReassignment(mDefaultRequest);
10528 final NetworkAgentInfo oldDefaultNetwork =
10529 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10530 final NetworkAgentInfo newDefaultNetwork =
10531 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010532
Chalard Jean5b409c72021-02-04 13:12:59 +090010533 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010534 // Maintain the illusion : since the legacy API only understands one network at a time,
10535 // if the default network changed, apps should see a disconnected broadcast for the
10536 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010537 if (oldDefaultNetwork != null) {
10538 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10539 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010540 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010541 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010542 // The new default network can be newly null if and only if the old default
10543 // network doesn't satisfy the default request any more because it lost a
10544 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010545 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010546 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010547 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010548 }
10549 }
10550
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010551 // Now that all the callbacks have been sent, send the legacy network broadcasts
10552 // as needed. This is necessary so that legacy requests correctly bind dns
10553 // requests to this network. The legacy users are listening for this broadcast
10554 // and will generally do a dns request so they can ensureRouteToHost and if
10555 // they do that before the callbacks happen they'll use the default network.
10556 //
10557 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10558 // callbacks, but if apps can receive the broadcast before the callback, they still might
10559 // have an inconsistent view of networking.
10560 //
10561 // This *does* introduce a race where if the user uses the new api
10562 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10563 // they may get old info. Reverse this after the old startUsing api is removed.
10564 // This is on top of the multiple intent sequencing referenced in the todo above.
10565 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010566 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010567 addNetworkToLegacyTypeTracker(nai);
10568 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010569 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010570 }
10571
Chalard Jean0354d8c2021-01-12 10:58:56 +090010572 private void issueNetworkNeeds() {
10573 ensureRunningOnConnectivityServiceThread();
10574 for (final NetworkOfferInfo noi : mNetworkOffers) {
10575 issueNetworkNeeds(noi);
10576 }
10577 }
10578
10579 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10580 ensureRunningOnConnectivityServiceThread();
10581 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10582 informOffer(nri, noi.offer, mNetworkRanker);
10583 }
10584 }
10585
10586 /**
10587 * Inform a NetworkOffer about any new situation of a request.
10588 *
10589 * This function handles updates to offers. A number of events may happen that require
10590 * updating the registrant for this offer about the situation :
10591 * • The offer itself was updated. This may lead the offer to no longer being able
10592 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10593 * or conversely being strengthened enough to beat the satisfier (and therefore
10594 * start being needed)
10595 * • The network satisfying a request changed (including cases where the request
10596 * starts or stops being satisfied). The new network may be a stronger or weaker
10597 * match than the old one, possibly affecting whether the offer is needed.
10598 * • The network satisfying a request updated their score. This may lead the offer
10599 * to no longer be able to beat it if the current satisfier got better, or
10600 * conversely start being a good choice if the current satisfier got weaker.
10601 *
10602 * @param nri The request
10603 * @param offer The offer. This may be an updated offer.
10604 */
10605 private static void informOffer(@NonNull NetworkRequestInfo nri,
10606 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10607 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10608 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010609
10610 // Multi-layer requests have a currently active request, the one being satisfied.
10611 // Since the system will try to bring up a better network than is currently satisfying
10612 // the request, NetworkProviders need to be told the offers matching the requests *above*
10613 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10614 // not needed, and the offer is needed for the active request iff the offer can beat
10615 // the satisfier.
10616 // For non-multilayer requests, the logic above gracefully degenerates to only the
10617 // last case.
10618 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10619 // providers that the offer is needed for this request, until the active request is found.
10620 // In a second phase, deal with the currently active request. In a third phase, inform
10621 // the providers that offer is unneeded for the remaining requests.
10622
10623 // First phase : inform providers of all requests above the active request.
10624 int i;
10625 for (i = 0; nri.mRequests.size() > i; ++i) {
10626 final NetworkRequest request = nri.mRequests.get(i);
10627 if (activeRequest == request) break; // Found the active request : go to phase 2
10628 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10629 // Since this request is higher-priority than the one currently satisfied, if the
10630 // offer can satisfy it, the provider should try and bring up the network for sure ;
10631 // no need to even ask the ranker – an offer that can satisfy is always better than
10632 // no network. Hence tell the provider so unless it already knew.
10633 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10634 offer.onNetworkNeeded(request);
10635 }
10636 }
10637
10638 // Second phase : deal with the active request (if any)
10639 if (null != activeRequest && activeRequest.isRequest()) {
10640 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010641 // If an offer can satisfy the request, it is considered needed if it is currently
10642 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010643 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010644 && satisfier.factorySerialNumber == offer.providerId
10645 && activeRequest.canBeSatisfiedBy(offer.caps);
10646 final boolean newNeeded = currentlyServing
10647 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010648 if (newNeeded != oldNeeded) {
10649 if (newNeeded) {
10650 offer.onNetworkNeeded(activeRequest);
10651 } else {
10652 // The offer used to be able to beat the satisfier. Now it can't.
10653 offer.onNetworkUnneeded(activeRequest);
10654 }
10655 }
10656 }
10657
10658 // Third phase : inform the providers that the offer isn't needed for any request
10659 // below the active one.
10660 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10661 final NetworkRequest request = nri.mRequests.get(i);
10662 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10663 // Since this request is lower-priority than the one currently satisfied, if the
10664 // offer can satisfy it, the provider should not try and bring up the network.
10665 // Hence tell the provider so unless it already knew.
10666 if (offer.neededFor(request)) {
10667 offer.onNetworkUnneeded(request);
10668 }
10669 }
10670 }
10671
Chalard Jean61c79252019-11-07 23:07:32 +090010672 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10673 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10674 NetworkRequest nr = nai.requestAt(i);
10675 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10676 // legacy type tracker filters out repeat adds
10677 mLegacyTypeTracker.add(nr.legacyType, nai);
10678 }
10679 }
10680
10681 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010682 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010683 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10684 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10685 if (nai.isVPN()) {
10686 mLegacyTypeTracker.add(TYPE_VPN, nai);
10687 }
10688 }
10689
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010690 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010691 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010692 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010693 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010694 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010695 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010696
Chalard Jean254bd162022-08-25 13:04:51 +090010697 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010698 // Don't repeat publish.
10699 if (newInetCondition == mDefaultInetConditionPublished) return;
10700
10701 mDefaultInetConditionPublished = newInetCondition;
10702 sendInetConditionBroadcast(nai.networkInfo);
10703 }
10704
Chalard Jeand61375d2020-01-14 22:46:36 +090010705 @NonNull
10706 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10707 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010708 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010709 final boolean suspended =
10710 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10711 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10712 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10713 // state. This is because the network could have been suspended before connecting,
10714 // or it could be disconnecting while being suspended, and in both these cases
10715 // the state should not be overridden. Note that the only detailed state that
10716 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10717 // worry about multiple different substates of CONNECTED.
10718 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10719 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010720 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10721 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10722 // network agent is created, then goes to suspended, then goes out of suspended without
10723 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010724 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010725 ? NetworkInfo.DetailedState.CONNECTED
10726 : NetworkInfo.DetailedState.CONNECTING,
10727 info.getReason(),
10728 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010729 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010730 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010731 return newInfo;
10732 }
10733
10734 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10735 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10736
Erik Kline99f301b2017-02-15 19:59:17 +090010737 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010738 NetworkInfo oldInfo = null;
10739 synchronized (networkAgent) {
10740 oldInfo = networkAgent.networkInfo;
10741 networkAgent.networkInfo = newInfo;
10742 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010743
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010744 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010745 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10746 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010747 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010748
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010749 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010750 // A network that has just connected has zero requests and is thus a foreground network.
10751 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10752
Luke Huangfdd11f82019-04-09 18:41:49 +080010753 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010754
10755 networkAgent.setCreated();
10756
10757 // If the network is created immediately on register, then apply the LinkProperties now.
10758 // Otherwise, this is done further down when the network goes into connected state.
10759 // Applying the LinkProperties means that the network is ready to carry traffic -
10760 // interfaces and routing rules have been added, DNS servers programmed, etc.
10761 // For VPNs, this must be done before the capabilities are updated, because as soon as
10762 // that happens, UIDs are routed to the network.
10763 if (shouldCreateNetworksImmediately()) {
10764 applyInitialLinkProperties(networkAgent);
10765 }
10766
10767 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10768 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010769 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010770 // Initialize the network's capabilities to their starting values according to the
10771 // underlying networks. This ensures that the capabilities are correct before
10772 // anything happens to the network.
10773 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010774 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010775 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010776 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010777 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010778 }
10779
Chalard Jean254bd162022-08-25 13:04:51 +090010780 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10781 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010782
lucaslin45e639b2019-04-03 17:09:28 +080010783 // NetworkCapabilities need to be set before sending the private DNS config to
10784 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010785 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10786
Erik Kline9a62f012018-03-21 07:18:33 -070010787 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010788 if (!shouldCreateNetworksImmediately()) {
10789 applyInitialLinkProperties(networkAgent);
10790 } else {
10791 // The network was created when the agent registered, and the LinkProperties are
10792 // already up-to-date. However, updateLinkProperties also makes some changes only
10793 // when the network connects. Apply those changes here. On T and below these are
10794 // handled by the applyInitialLinkProperties call just above.
10795 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10796 // If something depends on both LinkProperties and connected state, it should be in
10797 // this method as well.
10798 networkAgent.clatd.update();
10799 updateProxy(networkAgent.linkProperties, null);
10800 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010801
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010802 // If a rate limit has been configured and is applicable to this network (network
10803 // provides internet connectivity), apply it. The tc police filter cannot be attached
10804 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010805 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010806 // Note: in case of a system server crash, the NetworkController constructor in netd
10807 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10808 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10809 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10810 mIngressRateLimit);
10811 }
10812
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010813 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10814 // command must be sent after updating LinkProperties to maximize chances of
10815 // NetworkMonitor seeing the correct LinkProperties when starting.
10816 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010817 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010818 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010819 }
Chalard Jeand4900722022-02-06 12:25:38 +090010820 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10821 params.networkAgentConfig = networkAgent.networkAgentConfig;
10822 params.networkCapabilities = networkAgent.networkCapabilities;
10823 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10824 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010825 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10826 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10827 // call that would cause a Log.wtf to be emitted from the system_server process, and
10828 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10829 // process to check the interface version, just use an SDK check. NetworkStack will
10830 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010831 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010832 networkAgent.networkMonitor().notifyNetworkConnected(params);
10833 } else {
10834 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10835 params.networkCapabilities);
10836 }
Chalard Jean0f141332023-06-05 19:26:17 +090010837 final long evaluationDelay;
10838 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10839 // If the network is anything other than pure wifi, use the default timeout.
10840 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10841 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10842 // If the network is explicitly selected, use the default timeout because it's
10843 // shorter and the user is likely staring at the screen expecting it to validate
10844 // right away.
10845 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10846 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10847 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10848 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10849 } else {
10850 // It's wifi, automatically connected, and bad wifi is preferred : use the
10851 // longer timeout to avoid the device switching to captive portals with bad
10852 // signal or very slow response.
10853 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10854 }
10855 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010856
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010857 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10858 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10859 // capabilities, so it only needs to be done once on initial connect, not every time the
10860 // network's capabilities change. Note that we do this before rematching the network,
10861 // so we could decide to tear it down immediately afterwards. That's fine though - on
10862 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10863 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010864 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010865
junyulai0ac374f2020-12-14 18:41:52 +080010866 // Before first rematching networks, put an inactivity timer without any request, this
10867 // allows {@code updateInactivityState} to update the state accordingly and prevent
10868 // tearing down for any {@code unneeded} evaluation in this period.
10869 // Note that the timer will not be rescheduled since the expiry time is
10870 // fixed after connection regardless of the network satisfying other requests or not.
10871 // But it will be removed as soon as the network satisfies a request for the first time.
10872 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10873 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010874 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010875
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010876 if (mTrackMultiNetworkActivities) {
10877 // Start tracking activity of this network.
10878 // This must be called before rematchAllNetworksAndRequests since the network
10879 // should be tracked when the network becomes the default network.
10880 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10881 // can be triggered later if this network becomes the default network.
10882 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10883 }
10884
Paul Jensen05e85ee2014-09-11 11:00:39 -040010885 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010886 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010887
10888 // This has to happen after matching the requests, because callbacks are just requests.
10889 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010890 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010891 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010892 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010893 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010894 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010895 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010896 if (networkAgent.isVPN()) {
10897 // As the active or bound network changes for apps, broadcast the default proxy, as
10898 // apps may need to update their proxy data. This is called after disconnecting from
10899 // VPN to make sure we do not broadcast the old proxy data.
10900 // TODO(b/122649188): send the broadcast only to VPN users.
10901 mProxyTracker.sendProxyBroadcast();
10902 }
Chalard Jean254bd162022-08-25 13:04:51 +090010903 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10904 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010905 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010906 }
10907 }
10908
Chalard Jean28018572020-12-21 18:36:52 +090010909 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010910 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10911 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010912 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010913 }
10914
Erik Kline99f301b2017-02-15 19:59:17 +090010915 // Notify only this one new request of the current state. Transfer all the
10916 // current state by calling NetworkCapabilities and LinkProperties callbacks
10917 // so that callers can be guaranteed to have as close to atomicity in state
10918 // transfer as can be supported by this current API.
10919 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010920 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010921 if (nri.mPendingIntent != null) {
10922 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10923 // Attempt no subsequent state pushes where intents are involved.
10924 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010925 }
Erik Kline99f301b2017-02-15 19:59:17 +090010926
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010927 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010928 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010929 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10930 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10931 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010932 }
10933
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010934 // Notify the requests on this NAI that the network is now lingered.
10935 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010936 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010937 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10938 }
10939
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010940 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10941 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10942 return vpnBlocked
10943 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10944 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10945 }
10946
10947 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10948 if (blockedReasons == BLOCKED_REASON_NONE) {
10949 mUidBlockedReasons.delete(uid);
10950 } else {
10951 mUidBlockedReasons.put(uid, blockedReasons);
10952 }
10953 }
10954
junyulaif2c67e42018-08-07 19:50:45 +080010955 /**
10956 * Notify of the blocked state apps with a registered callback matching a given NAI.
10957 *
10958 * Unlike other callbacks, blocked status is different between each individual uid. So for
10959 * any given nai, all requests need to be considered according to the uid who filed it.
10960 *
10961 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010962 * @param oldMetered True if the previous network capabilities were metered.
10963 * @param newMetered True if the current network capabilities are metered.
10964 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10965 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010966 */
10967 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010968 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10969 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010970
10971 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10972 NetworkRequest nr = nai.requestAt(i);
10973 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010974
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010975 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10976 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10977 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010978 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010979 : oldVpnBlocked;
10980
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010981 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10982 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10983 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010984 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010985 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010986 }
10987 }
10988 }
10989
10990 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010991 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010992 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010993 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010994 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010995 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010996 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010997 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010998 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010999
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011000 final int oldBlockedState = getBlockedState(
11001 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
11002 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
11003 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080011004 continue;
junyulaif2c67e42018-08-07 19:50:45 +080011005 }
junyulaif2c67e42018-08-07 19:50:45 +080011006 for (int i = 0; i < nai.numNetworkRequests(); i++) {
11007 NetworkRequest nr = nai.requestAt(i);
11008 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011009 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011010 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
11011 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080011012 }
11013 }
11014 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011015 }
11016
Chalard Jean3a3f5f22019-04-10 23:07:55 +090011017 @VisibleForTesting
11018 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090011019 // The NetworkInfo we actually send out has no bearing on the real
11020 // state of affairs. For example, if the default connection is mobile,
11021 // and a request for HIPRI has just gone away, we need to pretend that
11022 // HIPRI has just disconnected. So we need to set the type to HIPRI and
11023 // the state to DISCONNECTED, even though the network is of type MOBILE
11024 // and is still connected.
11025 NetworkInfo info = new NetworkInfo(nai.networkInfo);
11026 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090011027 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070011028 if (state != DetailedState.DISCONNECTED) {
11029 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090011030 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011031 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070011032 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070011033 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
11034 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
11035 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
11036 if (info.isFailover()) {
11037 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
11038 nai.networkInfo.setFailover(false);
11039 }
11040 if (info.getReason() != null) {
11041 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
11042 }
11043 if (info.getExtraInfo() != null) {
11044 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
11045 }
11046 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090011047 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080011048 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070011049 if (newDefaultAgent != null) {
11050 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
11051 newDefaultAgent.networkInfo);
11052 } else {
11053 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
11054 }
11055 }
11056 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
11057 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090011058 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011059 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090011060 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011061 }
11062 }
11063 }
11064
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011065 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090011066 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090011067 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090011068 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090011069 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090011070 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
11071 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011072 NetworkRequestInfo nri = mNetworkRequests.get(nr);
11073 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011074 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011075 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011076 } else {
11077 sendPendingIntentForRequest(nri, networkAgent, notifyType);
11078 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011079 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011080 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070011081
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011082 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
11083 notifyNetworkCallbacks(networkAgent, notifyType, 0);
11084 }
11085
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011086 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090011087 * Returns the list of all interfaces that could be used by network traffic that does not
11088 * explicitly specify a network. This includes the default network, but also all VPNs that are
11089 * currently connected.
11090 *
11091 * Must be called on the handler thread.
11092 */
junyulaie7c7d2a2021-01-26 15:29:15 +080011093 @NonNull
11094 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080011095 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080011096 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080011097 final Set<Integer> activeNetIds = new ArraySet<>();
11098 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
11099 if (nri.isBeingSatisfied()) {
11100 activeNetIds.add(nri.getSatisfier().network().netId);
11101 }
11102 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090011103 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090011104 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090011105 defaultNetworks.add(nai.network);
11106 }
11107 }
junyulaie7c7d2a2021-01-26 15:29:15 +080011108 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090011109 }
11110
11111 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090011112 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
11113 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011114 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080011115 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080011116 ensureRunningOnConnectivityServiceThread();
11117 String activeIface = null;
11118 LinkProperties activeLinkProperties = getActiveLinkProperties();
11119 if (activeLinkProperties != null) {
11120 activeIface = activeLinkProperties.getInterfaceName();
11121 }
Benedict Wong9308cd32019-06-12 17:46:31 +000011122
junyulai2050bed2021-01-23 09:46:34 +080011123 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011124 try {
junyulaide41fc22021-01-22 22:46:01 +080011125 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090011126 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080011127 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
11128 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011129 } catch (Exception ignored) {
11130 }
11131 }
11132
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070011133 @Override
Udam Sainicd645462016-01-04 12:16:14 -080011134 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080011135 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090011136 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090011137 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011138
11139 if (!TextUtils.isEmpty(settingUrl)) {
11140 return settingUrl;
11141 }
11142
11143 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011144 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011145 if (!TextUtils.isEmpty(settingUrl)) {
11146 return settingUrl;
11147 }
11148
11149 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080011150 }
11151
11152 @Override
junyulai070f9ff2019-01-16 20:23:34 +080011153 public void startNattKeepalive(Network network, int intervalSeconds,
11154 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011155 enforceKeepalivePermission();
11156 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080011157 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000011158 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
11159 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000011160 // false and set the underpinned network to null because there is no way and no
11161 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
11162 // deprecated method.
11163 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011164 }
11165
11166 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011167 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080011168 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000011169 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070011170 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080011171 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011172 mKeepaliveTracker.startNattKeepalive(
11173 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000011174 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
11175 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070011176 } finally {
11177 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11178 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011179 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11180 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011181 }
11182 }
junyulaid05a1922019-01-15 11:32:44 +080011183 }
11184
11185 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011186 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080011187 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070011188 try {
11189 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080011190 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011191 mKeepaliveTracker.startTcpKeepalive(
11192 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
11193 } finally {
11194 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11195 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011196 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11197 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011198 }
11199 }
junyulai0835a1e2019-01-08 20:04:33 +080011200 }
11201
11202 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011203 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011204 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011205 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
11206 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011207 }
11208
11209 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090011210 public int[] getSupportedKeepalives() {
11211 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
11212 // Backwards compatibility with CTS 13
11213 android.Manifest.permission.QUERY_ALL_PACKAGES);
11214
11215 return BinderUtils.withCleanCallingIdentity(() ->
11216 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
11217 }
11218
11219 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070011220 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080011221 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070011222
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011223 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080011224 final long token = Binder.clearCallingIdentity();
11225 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011226 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
11227 UserHandle.getUserHandleForUid(uid))) {
11228 return;
11229 }
11230
Heemin Seogdb8489d2019-06-12 09:21:44 -070011231 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
11232 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011233
11234 // Turn airplane mode off
11235 setAirplaneMode(false);
11236
11237 // restore private DNS settings to default mode (opportunistic)
11238 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
11239 UserHandle.getUserHandleForUid(uid))) {
11240 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
11241 PRIVATE_DNS_MODE_OPPORTUNISTIC);
11242 }
11243
11244 Settings.Global.putString(mContext.getContentResolver(),
11245 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080011246 } finally {
11247 Binder.restoreCallingIdentity(token);
11248 }
Stuart Scottd5463642015-04-02 18:00:02 -070011249 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040011250
Ricky Wai7097cc92018-01-23 04:09:45 +000011251 @Override
11252 public byte[] getNetworkWatchlistConfigHash() {
11253 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
11254 if (nwm == null) {
11255 loge("Unable to get NetworkWatchlistManager");
11256 return null;
11257 }
11258 // Redirect it to network watchlist service to access watchlist file and calculate hash.
11259 return nwm.getWatchlistConfigHash();
11260 }
11261
Hugo Benichibe0c7652016-05-31 16:28:06 +090011262 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090011263 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080011264 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090011265 }
Hugo Benichif4210292017-04-21 15:07:12 +090011266
11267 private static boolean toBool(int encodedBoolean) {
11268 return encodedBoolean != 0; // Only 0 means false.
11269 }
11270
11271 private static int encodeBool(boolean b) {
11272 return b ? 1 : 0;
11273 }
mswest4632928412018-03-12 10:34:34 -070011274
11275 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011276 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
11277 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
11278 @NonNull String[] args) {
11279 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11280 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011281 }
11282
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011283 private class ShellCmd extends BasicShellCommandHandler {
Suprabh Shukla22ea1662024-02-08 16:06:01 -080011284
11285 private Boolean parseBooleanArgument(final String arg) {
11286 if ("true".equals(arg)) {
11287 return true;
11288 } else if ("false".equals(arg)) {
11289 return false;
11290 } else {
11291 getOutPrintWriter().println("Invalid boolean argument: " + arg);
11292 return null;
11293 }
11294 }
11295
11296 private Integer parseIntegerArgument(final String arg) {
11297 try {
11298 return Integer.valueOf(arg);
11299 } catch (NumberFormatException ne) {
11300 getOutPrintWriter().println("Invalid integer argument: " + arg);
11301 return null;
11302 }
11303 }
11304
mswest4632928412018-03-12 10:34:34 -070011305 @Override
11306 public int onCommand(String cmd) {
11307 if (cmd == null) {
11308 return handleDefaultCommands(cmd);
11309 }
11310 final PrintWriter pw = getOutPrintWriter();
11311 try {
11312 switch (cmd) {
11313 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011314 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11315 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011316 final String action = getNextArg();
11317 if ("enable".equals(action)) {
11318 setAirplaneMode(true);
11319 return 0;
11320 } else if ("disable".equals(action)) {
11321 setAirplaneMode(false);
11322 return 0;
11323 } else if (action == null) {
11324 final ContentResolver cr = mContext.getContentResolver();
11325 final int enabled = Settings.Global.getInt(cr,
11326 Settings.Global.AIRPLANE_MODE_ON);
11327 pw.println(enabled == 0 ? "disabled" : "enabled");
11328 return 0;
11329 } else {
11330 onHelp();
11331 return -1;
11332 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011333 case "set-chain3-enabled": {
11334 final Boolean enabled = parseBooleanArgument(getNextArg());
11335 if (null == enabled) {
11336 onHelp();
11337 return -1;
11338 }
11339 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11340 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11341 enabled);
11342 return 0;
11343 }
11344 case "get-chain3-enabled": {
11345 final boolean chainEnabled = getFirewallChainEnabled(
11346 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11347 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11348 return 0;
11349 }
11350 case "set-package-networking-enabled": {
11351 final Boolean enabled = parseBooleanArgument(getNextArg());
11352 final String packageName = getNextArg();
11353 if (null == enabled || null == packageName) {
11354 onHelp();
11355 return -1;
11356 }
11357 // Throws NameNotFound if the package doesn't exist.
11358 final int appId = setPackageFirewallRule(
11359 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11360 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11361 final String msg = (enabled ? "Enabled" : "Disabled")
11362 + " networking for " + packageName + ", appId " + appId;
11363 Log.i(TAG, msg);
11364 pw.println(msg);
11365 return 0;
11366 }
11367 case "get-package-networking-enabled": {
11368 final String packageName = getNextArg();
11369 final int rule = getPackageFirewallRule(
11370 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11371 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11372 pw.println(packageName + ":" + "allow");
11373 } else if (FIREWALL_RULE_DENY == rule) {
11374 pw.println(packageName + ":" + "deny");
11375 } else {
11376 throw new IllegalStateException("Unknown rule " + rule + " for package "
11377 + packageName);
11378 }
11379 return 0;
11380 }
Suprabh Shukla22ea1662024-02-08 16:06:01 -080011381 case "set-background-networking-enabled-for-uid": {
11382 final Integer uid = parseIntegerArgument(getNextArg());
11383 final Boolean enabled = parseBooleanArgument(getNextArg());
11384 if (null == enabled || null == uid) {
11385 onHelp();
11386 return -1;
11387 }
11388 final int rule = enabled ? FIREWALL_RULE_ALLOW : FIREWALL_RULE_DEFAULT;
11389 setUidFirewallRule(FIREWALL_CHAIN_BACKGROUND, uid, rule);
11390 final String msg = (enabled ? "Enabled" : "Disabled")
11391 + " background networking for uid " + uid;
11392 Log.i(TAG, msg);
11393 pw.println(msg);
11394 return 0;
11395 }
11396 case "get-background-networking-enabled-for-uid": {
11397 final Integer uid = parseIntegerArgument(getNextArg());
11398 if (null == uid) {
11399 onHelp();
11400 return -1;
11401 }
11402 final int rule = getUidFirewallRule(FIREWALL_CHAIN_BACKGROUND, uid);
11403 if (FIREWALL_RULE_ALLOW == rule) {
11404 pw.println(uid + ": allow");
11405 } else if (FIREWALL_RULE_DENY == rule || FIREWALL_RULE_DEFAULT == rule) {
11406 pw.println(uid + ": deny");
11407 } else {
11408 throw new IllegalStateException(
11409 "Unknown rule " + rule + " for uid " + uid);
11410 }
11411 return 0;
11412 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011413 case "reevaluate":
11414 // Usage : adb shell cmd connectivity reevaluate <netId>
11415 // If netId is omitted, then reevaluate the default network
11416 final String netId = getNextArg();
11417 final NetworkAgentInfo nai;
11418 if (null == netId) {
11419 // Note that the command is running on the wrong thread to call this,
11420 // so this could in principle return stale data. But it can't crash.
11421 nai = getDefaultNetwork();
11422 } else {
11423 // If netId can't be parsed, this throws NumberFormatException, which
11424 // is passed back to adb who prints it.
11425 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11426 }
11427 if (null == nai) {
11428 pw.println("Unknown network (net ID not found or no default network)");
11429 return 0;
11430 }
11431 Log.d(TAG, "Reevaluating network " + nai.network);
11432 reportNetworkConnectivity(nai.network, !nai.isValidated());
11433 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011434 case "bpf-get-cgroup-program-id": {
11435 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11436 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11437 // for more detail.
11438 // If type can't be parsed, this throws NumberFormatException, which
11439 // is passed back to adb who prints it.
11440 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011441 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011442 pw.println(ret);
11443 return 0;
11444 }
mswest4632928412018-03-12 10:34:34 -070011445 default:
11446 return handleDefaultCommands(cmd);
11447 }
11448 } catch (Exception e) {
11449 pw.println(e);
11450 }
11451 return -1;
11452 }
11453
11454 @Override
11455 public void onHelp() {
11456 PrintWriter pw = getOutPrintWriter();
11457 pw.println("Connectivity service commands:");
11458 pw.println(" help");
11459 pw.println(" Print this help text.");
11460 pw.println(" airplane-mode [enable|disable]");
11461 pw.println(" Turn airplane mode on or off.");
11462 pw.println(" airplane-mode");
11463 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011464 pw.println(" set-chain3-enabled [true|false]");
11465 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11466 pw.println(" get-chain3-enabled");
11467 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11468 pw.println(" set-package-networking-enabled [true|false] [package name]");
11469 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11470 + " no effect if the chain is disabled.");
11471 pw.println(" get-package-networking-enabled [package name]");
11472 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
Suprabh Shukla22ea1662024-02-08 16:06:01 -080011473 pw.println(" set-background-networking-enabled-for-uid [uid] [true|false]");
11474 pw.println(" Set the allow bit in FIREWALL_CHAIN_BACKGROUND for the given uid.");
11475 pw.println(" get-background-networking-enabled-for-uid [uid]");
11476 pw.println(" Get the allow bit in FIREWALL_CHAIN_BACKGROUND for the given uid.");
mswest4632928412018-03-12 10:34:34 -070011477 }
11478 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011479
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011480 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011481 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11482 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11483 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011484 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011485 }
11486
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011487 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11488 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011489 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11490 final TransportInfo newInfo = nc.getTransportInfo();
11491 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11492 return;
11493 }
11494 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011495 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011496 }
11497 }
11498
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011499 /**
11500 * @param connectionInfo the connection to resolve.
11501 * @return {@code uid} if the connection is found and the app has permission to observe it
11502 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11503 * connection is not found.
11504 */
11505 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011506 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11507 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11508 }
11509
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011510 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011511 connectionInfo.local, connectionInfo.remote);
11512
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011513 if (uid == INVALID_UID) return uid; // Not found.
11514
11515 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11516 // VPN, if any, that applies to the UID that owns the connection.
Junyu Lai71b51532024-02-01 10:39:01 +080011517 if (hasNetworkStackPermission()) return uid;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011518
11519 final NetworkAgentInfo vpn = getVpnForUid(uid);
11520 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011521 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011522 return INVALID_UID;
11523 }
11524
11525 return uid;
11526 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011527
Benedict Wong493e04b2018-11-09 14:45:34 -080011528 /**
11529 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11530 *
11531 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11532 */
11533 @Override
11534 public IBinder startOrGetTestNetworkService() {
11535 synchronized (mTNSLock) {
11536 TestNetworkService.enforceTestNetworkPermissions(mContext);
11537
11538 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011539 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011540 }
11541
11542 return mTNS;
11543 }
11544 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011545
Cody Kesting73708bf2019-12-18 10:57:50 -080011546 /**
11547 * Handler used for managing all Connectivity Diagnostics related functions.
11548 *
11549 * @see android.net.ConnectivityDiagnosticsManager
11550 *
11551 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11552 */
11553 @VisibleForTesting
11554 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011555 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11556
Cody Kesting73708bf2019-12-18 10:57:50 -080011557 /**
11558 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11559 * android.net.ConnectivityDiagnosticsManager}.
11560 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11561 * NetworkRequestInfo to be registered
11562 */
11563 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11564
11565 /**
11566 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11567 * android.net.ConnectivityDiagnosticsManager}.
11568 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11569 * arg1 = the uid of the caller
11570 */
11571 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11572
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011573 /**
11574 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011575 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011576 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11577 * NetworkMonitor.
11578 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011579 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011580 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011581
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011582 /**
11583 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11584 * been detected on the network.
11585 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11586 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11587 * arg2 = NetID.
11588 * data = PersistableBundle of extras passed from NetworkMonitor.
11589 */
11590 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11591
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011592 /**
11593 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11594 * the platform. This event will invoke {@link
11595 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11596 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011597 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011598 */
11599 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11600
Cody Kesting73708bf2019-12-18 10:57:50 -080011601 private ConnectivityDiagnosticsHandler(Looper looper) {
11602 super(looper);
11603 }
11604
11605 @Override
11606 public void handleMessage(Message msg) {
11607 switch (msg.what) {
11608 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11609 handleRegisterConnectivityDiagnosticsCallback(
11610 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11611 break;
11612 }
11613 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11614 handleUnregisterConnectivityDiagnosticsCallback(
11615 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11616 break;
11617 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011618 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011619 final ConnectivityReportEvent reportEvent =
11620 (ConnectivityReportEvent) msg.obj;
11621
Aaron Huang959d3642021-01-21 15:47:41 +080011622 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011623 break;
11624 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011625 case EVENT_DATA_STALL_SUSPECTED: {
11626 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011627 final Pair<Long, PersistableBundle> arg =
11628 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011629 if (nai == null) break;
11630
Aaron Huang959d3642021-01-21 15:47:41 +080011631 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011632 break;
11633 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011634 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011635 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011636 break;
11637 }
11638 default: {
11639 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11640 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011641 }
11642 }
11643 }
11644
11645 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11646 @VisibleForTesting
11647 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11648 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11649 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011650 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011651
11652 @VisibleForTesting
11653 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011654 @NonNull IConnectivityDiagnosticsCallback cb,
11655 @NonNull NetworkRequestInfo nri,
11656 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011657 mCb = cb;
11658 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011659 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011660 }
11661
11662 @Override
11663 public void binderDied() {
11664 log("ConnectivityDiagnosticsCallback IBinder died.");
11665 unregisterConnectivityDiagnosticsCallback(mCb);
11666 }
11667 }
11668
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011669 /**
11670 * Class used for sending information from {@link
11671 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11672 */
11673 private static class NetworkTestedResults {
11674 private final int mNetId;
11675 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011676 @Nullable private final String mRedirectUrl;
11677
11678 private NetworkTestedResults(
11679 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11680 mNetId = netId;
11681 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011682 mRedirectUrl = redirectUrl;
11683 }
11684 }
11685
11686 /**
11687 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11688 * ConnectivityDiagnosticsHandler}.
11689 */
11690 private static class ConnectivityReportEvent {
11691 private final long mTimestampMillis;
11692 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011693 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011694
Aaron Huang959d3642021-01-21 15:47:41 +080011695 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11696 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011697 mTimestampMillis = timestampMillis;
11698 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011699 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011700 }
11701 }
11702
Cody Kestingf1120be2020-08-03 18:01:40 -070011703 /**
11704 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11705 * ConnectivityDiagnosticsHandler}.
11706 */
11707 private static class ReportedNetworkConnectivityInfo {
11708 public final boolean hasConnectivity;
11709 public final boolean isNetworkRevalidating;
11710 public final int reporterUid;
11711 @NonNull public final NetworkAgentInfo nai;
11712
11713 private ReportedNetworkConnectivityInfo(
11714 boolean hasConnectivity,
11715 boolean isNetworkRevalidating,
11716 int reporterUid,
11717 @NonNull NetworkAgentInfo nai) {
11718 this.hasConnectivity = hasConnectivity;
11719 this.isNetworkRevalidating = isNetworkRevalidating;
11720 this.reporterUid = reporterUid;
11721 this.nai = nai;
11722 }
11723 }
11724
Cody Kesting73708bf2019-12-18 10:57:50 -080011725 private void handleRegisterConnectivityDiagnosticsCallback(
11726 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11727 ensureRunningOnConnectivityServiceThread();
11728
11729 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011730 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011731 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11732
James Mattis64b8b0f2020-11-24 17:40:49 -080011733 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11734 // confusing for these networks to change when an NRI is satisfied in another layer.
11735 if (nri.isMultilayerRequest()) {
11736 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11737 + "network requests.");
11738 }
11739
Cody Kesting73708bf2019-12-18 10:57:50 -080011740 // This means that the client registered the same callback multiple times. Do
11741 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011742 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011743 if (VDBG) log("Diagnostics callback is already registered");
11744
11745 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11746 // incremented when the NetworkRequestInfo is created as part of
11747 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011748 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011749 return;
11750 }
11751
Cody Kesting31f1ff62020-03-05 10:46:02 -080011752 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011753
11754 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011755 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011756 } catch (RemoteException e) {
11757 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011758 return;
11759 }
11760
11761 // Once registered, provide ConnectivityReports for matching Networks
11762 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11763 synchronized (mNetworkForNetId) {
11764 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11765 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011766 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11767 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011768 matchingNetworks.add(nai);
11769 }
11770 }
11771 }
11772 for (final NetworkAgentInfo nai : matchingNetworks) {
11773 final ConnectivityReport report = nai.getConnectivityReport();
11774 if (report == null) {
11775 continue;
11776 }
Junyu Lai71b51532024-02-01 10:39:01 +080011777 if (!hasConnectivityDiagnosticsPermissions(
Cody Kestingb77bf702020-02-12 14:50:58 -080011778 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11779 continue;
11780 }
11781
11782 try {
11783 cb.onConnectivityReportAvailable(report);
11784 } catch (RemoteException e) {
11785 // Exception while sending the ConnectivityReport. Move on to the next network.
11786 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011787 }
11788 }
11789
11790 private void handleUnregisterConnectivityDiagnosticsCallback(
11791 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11792 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011793 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011794
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011795 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11796 mConnectivityDiagnosticsCallbacks.remove(iCb);
11797 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011798 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11799 return;
11800 }
11801
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011802 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011803
Cody Kesting70fa2b22020-12-02 12:16:56 -080011804 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11805 // (if the Binder died)
11806 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11807 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011808 return;
11809 }
11810
Cody Kesting46cb1672020-03-04 13:35:20 -080011811 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11812 // incremented when the NetworkRequestInfo is created as part of
11813 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011814 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011815
Cody Kesting31f1ff62020-03-05 10:46:02 -080011816 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011817 }
11818
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011819 private void handleNetworkTestedWithExtras(
11820 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11821 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011822 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011823 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011824 final ConnectivityReport report =
11825 new ConnectivityReport(
11826 reportEvent.mNai.network,
11827 reportEvent.mTimestampMillis,
11828 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011829 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011830 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011831 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011832
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011833 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011834 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011835 for (final IConnectivityDiagnosticsCallback cb : results) {
11836 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011837 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011838 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011839 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011840 }
11841 }
11842 }
11843
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011844 private void handleDataStallSuspected(
11845 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11846 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011847 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011848 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011849 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011850 new DataStallReport(
11851 nai.network,
11852 timestampMillis,
11853 detectionMethod,
11854 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011855 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011856 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011857 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011858 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011859 for (final IConnectivityDiagnosticsCallback cb : results) {
11860 try {
11861 cb.onDataStallSuspected(report);
11862 } catch (RemoteException ex) {
11863 loge("Error invoking onDataStallSuspected", ex);
11864 }
11865 }
11866 }
11867
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011868 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011869 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11870 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11871 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11872
11873 // If the Network is being re-validated as a result of this call to
11874 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11875 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011876 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011877 getMatchingPermissionedCallbacks(
11878 nai,
11879 reportedNetworkConnectivityInfo.isNetworkRevalidating
11880 ? Process.INVALID_UID
11881 : reportedNetworkConnectivityInfo.reporterUid);
11882
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011883 for (final IConnectivityDiagnosticsCallback cb : results) {
11884 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011885 cb.onNetworkConnectivityReported(
11886 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011887 } catch (RemoteException ex) {
11888 loge("Error invoking onNetworkConnectivityReported", ex);
11889 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011890
11891 // If the Network isn't re-validating, also provide the cached report. If there is no
11892 // cached report, the Network is still being validated and a report will be sent once
11893 // validation is complete. Note that networks which never undergo validation will still
11894 // have a cached ConnectivityReport with RESULT_SKIPPED.
11895 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11896 try {
11897 cb.onConnectivityReportAvailable(cachedReport);
11898 } catch (RemoteException ex) {
11899 loge("Error invoking onConnectivityReportAvailable", ex);
11900 }
11901 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011902 }
11903 }
11904
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011905 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011906 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11907 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011908 sanitized.setUids(null);
11909 sanitized.setAdministratorUids(new int[0]);
11910 sanitized.setOwnerUid(Process.INVALID_UID);
11911 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011912 }
11913
Cody Kestingf1120be2020-08-03 18:01:40 -070011914 /**
11915 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11916 *
11917 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11918 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011919 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011920 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011921 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011922 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011923 mConnectivityDiagnosticsCallbacks.entrySet()) {
11924 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11925 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011926
James Mattis64b8b0f2020-11-24 17:40:49 -080011927 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011928 if (!nai.satisfies(nri.mRequests.get(0))) {
11929 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011930 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011931
11932 // UID for this callback must either be:
11933 // - INVALID_UID (which sends callbacks to all UIDs), or
11934 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11935 // notified as a result)
11936 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11937 continue;
11938 }
11939
Junyu Lai71b51532024-02-01 10:39:01 +080011940 if (!hasConnectivityDiagnosticsPermissions(
Cody Kestingf1120be2020-08-03 18:01:40 -070011941 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11942 continue;
11943 }
11944
11945 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011946 }
11947 return results;
11948 }
11949
Cody Kesting7474f672021-05-11 14:22:40 -070011950 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11951 @NonNull NetworkAgentInfo nai) {
11952 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11953 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11954 }
11955
Cody Kesting160ef392021-05-05 13:17:22 -070011956 private boolean hasLocationPermission(String packageName, int uid) {
11957 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11958 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11959 // call in a try-catch.
11960 try {
11961 if (!mLocationPermissionChecker.checkLocationPermission(
11962 packageName, null /* featureId */, uid, null /* message */)) {
11963 return false;
11964 }
11965 } catch (SecurityException e) {
11966 return false;
11967 }
11968
11969 return true;
11970 }
11971
11972 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11973 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011974 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011975 && virtual.networkCapabilities.getOwnerUid() == uid
11976 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11977 return true;
11978 }
11979 }
11980
11981 return false;
11982 }
11983
Junyu Lai71b51532024-02-01 10:39:01 +080011984 @CheckResult
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011985 @VisibleForTesting
Junyu Lai71b51532024-02-01 10:39:01 +080011986 boolean hasConnectivityDiagnosticsPermissions(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011987 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
Junyu Lai71b51532024-02-01 10:39:01 +080011988 if (hasNetworkStackPermission(callbackPid, callbackUid)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011989 return true;
11990 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011991 if (mAllowSysUiConnectivityReports
Junyu Lai71b51532024-02-01 10:39:01 +080011992 && hasSystemBarServicePermission(callbackPid, callbackUid)) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011993 return true;
11994 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011995
Cody Kesting160ef392021-05-05 13:17:22 -070011996 // Administrator UIDs also contains the Owner UID
11997 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11998 if (!CollectionUtils.contains(administratorUids, callbackUid)
11999 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012000 return false;
12001 }
12002
Cody Kesting7474f672021-05-11 14:22:40 -070012003 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
12004 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012005 }
12006
Cody Kestingd199a9d2019-12-17 12:55:28 -080012007 @Override
12008 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012009 @NonNull IConnectivityDiagnosticsCallback callback,
12010 @NonNull NetworkRequest request,
12011 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070012012 Objects.requireNonNull(callback, "callback must not be null");
12013 Objects.requireNonNull(request, "request must not be null");
12014 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
12015
Cody Kesting73708bf2019-12-18 10:57:50 -080012016 if (request.legacyType != TYPE_NONE) {
12017 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
12018 + " Please use NetworkCapabilities instead.");
12019 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090012020 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080012021 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080012022
12023 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
12024 // and administrator uids to be safe.
12025 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080012026 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080012027
12028 final NetworkRequest requestWithId =
12029 new NetworkRequest(
12030 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
12031
12032 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
12033 //
12034 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
12035 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
12036 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012037 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080012038 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012039 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080012040
12041 mConnectivityDiagnosticsHandler.sendMessage(
12042 mConnectivityDiagnosticsHandler.obtainMessage(
12043 ConnectivityDiagnosticsHandler
12044 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
12045 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080012046 }
12047
12048 @Override
12049 public void unregisterConnectivityDiagnosticsCallback(
12050 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012051 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080012052 mConnectivityDiagnosticsHandler.sendMessage(
12053 mConnectivityDiagnosticsHandler.obtainMessage(
12054 ConnectivityDiagnosticsHandler
12055 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090012056 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080012057 0,
12058 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080012059 }
Cody Kestingf53a0752020-04-15 12:33:28 -070012060
Yan Yanfe96dde2022-12-05 23:00:01 +000012061 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
12062 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
12063 if (underlyingNetworks == null) return false;
12064
12065 for (Network network : underlyingNetworks) {
12066 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
12067 return true;
12068 }
12069 }
12070 return false;
12071 }
12072
Cody Kestingf53a0752020-04-15 12:33:28 -070012073 @Override
12074 public void simulateDataStall(int detectionMethod, long timestampMillis,
12075 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070012076 Objects.requireNonNull(network, "network must not be null");
12077 Objects.requireNonNull(extras, "extras must not be null");
12078
paulhu3ffffe72021-09-16 10:15:22 +080012079 enforceAnyPermissionOf(mContext,
12080 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070012081 android.Manifest.permission.NETWORK_STACK);
12082 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000012083 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
12084 throw new SecurityException(
12085 "Data Stall simulation is only possible for test networks or networks built on"
12086 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070012087 }
12088
12089 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000012090 if (nai == null
12091 || (nai.creatorUid != mDeps.getCallingUid()
12092 && nai.creatorUid != Process.SYSTEM_UID)) {
12093 throw new SecurityException(
12094 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070012095 }
12096
Cody Kesting652e3ec2020-05-21 12:08:21 -070012097 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
12098 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
12099 // Data Stall information as a DataStallReportParcelable and passing to
12100 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
12101 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070012102 final DataStallReportParcelable p = new DataStallReportParcelable();
12103 p.timestampMillis = timestampMillis;
12104 p.detectionMethod = detectionMethod;
12105
12106 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
12107 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
12108 }
12109 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
12110 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
12111 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
12112 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
12113 }
12114
Serik Beketayevec8ad212020-12-07 22:43:07 -080012115 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070012116 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012117
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012118 /**
12119 * Class to hold the information for network activity change event from idle timers
12120 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
12121 */
12122 private static final class NetworkActivityParams {
12123 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012124 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
12125 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012126 public final int label;
12127 public final long timestampNs;
12128 // Uid represents the uid that was responsible for waking the radio.
12129 // -1 for no uid and uid is -1 if isActive is false.
12130 public final int uid;
12131
12132 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
12133 this.isActive = isActive;
12134 this.label = label;
12135 this.timestampNs = timestampNs;
12136 this.uid = uid;
12137 }
12138 }
12139
lucaslin66f44212021-02-23 01:12:55 +080012140 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
12141 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012142 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080012143 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012144 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
12145 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080012146 }
lucaslin37a16d92021-01-21 19:48:09 +080012147
12148 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090012149 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012150 mHandler.post(() -> {
12151 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090012152 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012153 }
12154 });
lucaslin37a16d92021-01-21 19:48:09 +080012155 }
12156
12157 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090012158 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012159 mHandler.post(() -> {
12160 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090012161 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012162 }
12163 });
lucaslin66f44212021-02-23 01:12:55 +080012164 }
12165 }
12166
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012167 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080012168 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
12169
12170 /**
12171 * Class used for updating network activity tracking with netd and notify network activity
12172 * changes.
12173 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012174 @VisibleForTesting
12175 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080012176 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080012177 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080012178 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012179 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080012180 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
12181 new RemoteCallbackList<>();
12182 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012183 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012184 // If there is no default network, default network is considered active to keep the existing
12185 // behavior. Initial value is used until first connect to the default network.
12186 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012187 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012188 // Key is netId. Value is configured idle timer information.
12189 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012190 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012191 // Store netIds of Wi-Fi networks whose idletimers report that they are active
12192 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
12193 // Store netIds of cellular networks whose idletimers report that they are active
12194 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080012195
Chalard Jean46bfbf02022-02-02 00:56:25 +090012196 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080012197 public final int timeout;
12198 public final int transportType;
12199
12200 IdleTimerParams(int timeout, int transport) {
12201 this.timeout = timeout;
12202 this.transportType = transport;
12203 }
12204 }
12205
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012206 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012207 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012208 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080012209 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012210 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012211 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012212 }
12213
12214 private void ensureRunningOnConnectivityServiceThread() {
12215 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
12216 throw new IllegalStateException("Not running on ConnectivityService thread: "
12217 + Thread.currentThread().getName());
12218 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012219 }
12220
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012221 /**
12222 * Update network activity and call BatteryStats to update radio power state if the
12223 * mobile or Wi-Fi activity is changed.
12224 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
12225 * mobile network is active since BatteryStatsService only maintains a single power state
12226 * for the mobile network.
12227 * The Wi-Fi network is also the same.
12228 *
12229 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
12230 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
12231 * transports.
12232 */
12233 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
12234 final boolean isActive, final int uid) {
12235 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
12236 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
12237 + transportType);
12238 return;
12239 }
12240 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
12241 ? mActiveWifiNetworks : mActiveCellularNetworks;
12242
12243 final boolean wasEmpty = activeNetworks.isEmpty();
12244 if (isActive) {
12245 activeNetworks.add(netId);
12246 } else {
12247 activeNetworks.remove(netId);
12248 }
12249
12250 if (wasEmpty != activeNetworks.isEmpty()) {
12251 updateRadioPowerState(isActive, transportType, uid);
12252 }
12253 }
12254
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012255 private void handleDefaultNetworkActivity(final int transportType,
12256 final boolean isActive, final long timestampNs) {
12257 mIsDefaultNetworkActive = isActive;
12258 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
12259 isActive, timestampNs);
12260 if (isActive) {
12261 reportNetworkActive();
12262 }
12263 }
12264
12265 private void handleReportNetworkActivityWithNetIdLabel(
12266 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012267 final int netId = activityParams.label;
12268 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012269 if (idleTimerParams == null) {
12270 // This network activity change is not tracked anymore
12271 // This can happen if netd callback post activity change event message but idle
12272 // timer is removed before processing this message.
12273 return;
12274 }
12275 // TODO: if a network changes transports, storing the transport type in the
12276 // IdleTimerParams is not correct. Consider getting it from the network's
12277 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012278 final int transportType = idleTimerParams.transportType;
12279 maybeUpdateRadioPowerState(netId, transportType,
12280 activityParams.isActive, activityParams.uid);
12281
12282 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
12283 // This activity change is not for the default network.
12284 return;
12285 }
12286
12287 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012288 activityParams.timestampNs);
12289 }
12290
12291 private void handleReportNetworkActivityWithTransportTypeLabel(
12292 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012293 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012294 // This activity change is not for the current default network.
12295 // This can happen if netd callback post activity change event message but
12296 // the default network is lost before processing this message.
12297 return;
12298 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012299 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
12300 activityParams.timestampNs);
12301 }
12302
12303 /**
12304 * Handle network activity change
12305 */
12306 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
12307 ensureRunningOnConnectivityServiceThread();
12308 if (mTrackMultiNetworkActivities) {
12309 handleReportNetworkActivityWithNetIdLabel(activityParams);
12310 } else {
12311 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080012312 }
12313 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012314
lucaslin1193a5d2021-01-21 02:04:15 +080012315 private void reportNetworkActive() {
12316 final int length = mNetworkActivityListeners.beginBroadcast();
12317 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
12318 try {
12319 for (int i = 0; i < length; i++) {
12320 try {
12321 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
12322 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012323 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080012324 }
12325 }
12326 } finally {
12327 mNetworkActivityListeners.finishBroadcast();
12328 }
12329 }
12330
lucaslin1a8b4c62021-01-21 02:02:55 +080012331 // This is deprecated and only to support legacy use cases.
12332 private int transportTypeToLegacyType(int type) {
12333 switch (type) {
12334 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012335 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012336 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012337 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012338 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012339 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012340 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012341 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012342 default:
12343 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12344 }
12345 return ConnectivityManager.TYPE_NONE;
12346 }
12347
12348 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12349 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12350 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12351 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12352 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12353 final long ident = Binder.clearCallingIdentity();
12354 try {
12355 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12356 RECEIVE_DATA_ACTIVITY_CHANGE,
12357 null /* resultReceiver */,
12358 null /* scheduler */,
12359 0 /* initialCode */,
12360 null /* initialData */,
12361 null /* initialExtra */);
12362 } finally {
12363 Binder.restoreCallingIdentity(ident);
12364 }
12365 }
12366
12367 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012368 * Get idle timer label
12369 */
12370 @VisibleForTesting
12371 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12372 final int netId, final int transportType) {
12373 return trackMultiNetworkActivities ? netId : transportType;
12374 }
12375
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012376 private boolean maybeCreateIdleTimer(
12377 String iface, int netId, int timeout, int transportType) {
12378 if (timeout <= 0 || iface == null) return false;
12379 try {
12380 final String label = Integer.toString(getIdleTimerLabel(
12381 mTrackMultiNetworkActivities, netId, transportType));
12382 mNetd.idletimerAddInterface(iface, timeout, label);
12383 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12384 return true;
12385 } catch (Exception e) {
12386 loge("Exception in createIdleTimer", e);
12387 return false;
12388 }
12389 }
12390
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012391 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012392 * Setup data activity tracking for the given network.
12393 *
12394 * Every {@code setupDataActivityTracking} should be paired with a
12395 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012396 *
12397 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012398 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012399 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012400 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012401 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012402 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012403
12404 final int timeout;
12405 final int type;
12406
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012407 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12408 // Do not track VPN network.
12409 return false;
12410 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012411 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12412 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012413 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012414 10);
12415 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12416 } else if (networkAgent.networkCapabilities.hasTransport(
12417 NetworkCapabilities.TRANSPORT_WIFI)) {
12418 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012419 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012420 15);
12421 type = NetworkCapabilities.TRANSPORT_WIFI;
12422 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012423 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012424 }
12425
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012426 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12427 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12428 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12429 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12430 // state only about a network that has an idletimer.
12431 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012432 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012433 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012434 }
12435
12436 /**
12437 * Remove data activity tracking when network disconnects.
12438 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012439 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12440 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012441 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012442 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012443 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12444
lucaslinb961efc2021-01-21 02:03:17 +080012445 if (iface == null) return;
12446
12447 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012448 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12449 // Do not track VPN network.
12450 return;
12451 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012452 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12453 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12454 type = NetworkCapabilities.TRANSPORT_WIFI;
12455 } else {
12456 return; // do not track any other networks
12457 }
12458
12459 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012460 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012461 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012462 if (params == null) {
12463 // IdleTimer is not added if the configured timeout is 0 or negative value
12464 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012465 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012466 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012467 final String label = Integer.toString(getIdleTimerLabel(
12468 mTrackMultiNetworkActivities, netId, params.transportType));
12469 // The call fails silently if no idle timer setup for this interface
12470 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012471 } catch (Exception e) {
12472 // You shall not crash!
12473 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012474 }
12475 }
12476
Motomu Utsumi6225d572023-05-29 15:08:57 +090012477 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12478 boolean hasIdleTimer) {
12479 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012480 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012481 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012482 // If only the default network is tracked, callbacks are called only when the
12483 // network has the idle timer.
12484 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012485 reportNetworkActive();
12486 }
12487 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012488 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012489 // If there is no default network, default network is considered active to keep the
12490 // existing behavior.
12491 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012492 }
12493 }
12494
lucaslin1a8b4c62021-01-21 02:02:55 +080012495 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012496 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012497 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012498 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012499 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012500 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012501 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12502 // first connected and remove when the network is disconnected.
12503 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12504 // becomes the default network and remove when the network becomes no longer the default
12505 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012506 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012507 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012508 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012509 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012510 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012511 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012512 removeDataActivityTracking(oldNetwork);
12513 }
12514 }
lucaslinb961efc2021-01-21 02:03:17 +080012515
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012516 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012517 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12518 switch (transportType) {
12519 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012520 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012521 break;
12522 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012523 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012524 break;
12525 default:
12526 logw("Untracked transport type:" + transportType);
12527 }
12528 }
lucaslin1193a5d2021-01-21 02:04:15 +080012529
12530 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012531 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012532 }
12533
12534 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12535 mNetworkActivityListeners.register(l);
12536 }
12537
12538 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12539 mNetworkActivityListeners.unregister(l);
12540 }
lucaslin012f7a12021-01-21 02:04:35 +080012541
12542 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012543 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012544 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012545 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012546 pw.println("Idle timers:");
12547 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012548 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12549 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12550 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012551 pw.print(" timeout="); pw.print(params.timeout);
12552 pw.print(" type="); pw.println(params.transportType);
12553 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012554 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12555 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012556 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012557 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12558 // be accessed from handler thread, except dump(). As dump() is never called in
12559 // normal usage, it would be needlessly expensive to lock the collection only for
12560 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012561 // So catching the exception and logging.
12562 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012563 }
12564 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012565 }
James Mattis47db0582021-01-01 14:13:35 -080012566
Daniel Brightf9e945b2020-06-15 16:10:01 -070012567 /**
12568 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12569 *
12570 * @param socketInfo the socket information
12571 * @param callback the callback to register
12572 */
12573 @Override
12574 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12575 @NonNull final IQosCallback callback) {
12576 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12577 if (nai == null || nai.networkCapabilities == null) {
12578 try {
12579 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12580 } catch (final RemoteException ex) {
12581 loge("registerQosCallbackInternal: RemoteException", ex);
12582 }
12583 return;
12584 }
12585 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12586 }
12587
12588 /**
12589 * Register a {@link IQosCallback} with base {@link QosFilter}.
12590 *
12591 * @param filter the filter to register
12592 * @param callback the callback to register
12593 * @param nai the agent information related to the filter's network
12594 */
12595 @VisibleForTesting
12596 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12597 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012598 Objects.requireNonNull(filter, "filter must be non-null");
12599 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012600
12601 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012602 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12603 // on this network is unregistered when the app loses permission or b) no QoS
12604 // callbacks are sent for restricted networks unless the app currently has permission
12605 // to access restricted networks.
12606 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012607 }
12608 mQosCallbackTracker.registerCallback(callback, filter, nai);
12609 }
12610
12611 /**
12612 * Unregisters the given callback.
12613 *
12614 * @param callback the callback to unregister
12615 */
12616 @Override
12617 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012618 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012619 mQosCallbackTracker.unregisterCallback(callback);
12620 }
James Mattis47db0582021-01-01 14:13:35 -080012621
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012622 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12623 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12624 // Enterprise device can be fully managed like device owner and such use case
12625 // also should be supported. Calling app check for work profile and fully managed device
12626 // is already done in DevicePolicyManager.
12627 // This check is an extra caution to be sure device is fully managed or not.
12628 final UserManager um = mContext.getSystemService(UserManager.class);
12629 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12630 if (um.isManagedProfile(profile.getIdentifier())) {
12631 return true;
12632 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012633 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012634 return false;
12635 }
12636
James Mattis45d81842021-01-10 14:24:24 -080012637 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012638 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012639 *
12640 * See the documentation for the individual preferences for a description of the supported
12641 * behaviors.
12642 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012643 * @param profile If the device owner is set, any profile is allowed.
12644 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012645 * @param preferences the list of profile network preferences for the
12646 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012647 * @param listener an optional listener to listen for completion of the operation.
12648 */
12649 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012650 public void setProfileNetworkPreferences(
12651 @NonNull final UserHandle profile,
12652 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012653 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012654 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012655 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012656
12657 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012658 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12659 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12660 .build();
12661 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012662 }
12663
paulhu3ffffe72021-09-16 10:15:22 +080012664 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012665 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012666 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012667 }
12668 if (profile.getIdentifier() < 0) {
12669 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12670 + "UserHandle.CURRENT not supported)");
12671 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012672 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12673 throw new IllegalArgumentException("Profile must be a managed profile "
12674 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012675 }
paulhuaa0743d2021-05-26 21:56:03 +080012676
Chalard Jean0606fc82022-12-14 20:34:43 +090012677 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012678 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012679 for (final ProfileNetworkPreference preference : preferences) {
12680 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012681 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012682 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012683 switch (preference.getPreference()) {
12684 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12685 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012686 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012687 if (preference.getPreferenceEnterpriseId() != 0) {
12688 throw new IllegalArgumentException(
12689 "Invalid enterprise identifier in setProfileNetworkPreferences");
12690 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012691 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012692 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12693 blockingNonEnterprise = true;
12694 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012695 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12696 allowFallback = false;
12697 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012698 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012699 // This code is needed even though there is a check later on,
12700 // because isRangeAlreadyInPreferenceList assumes that every preference
12701 // has a UID list.
12702 if (hasDefaultPreference) {
12703 throw new IllegalArgumentException(
12704 "Default profile preference should not be set along with other "
12705 + "preference");
12706 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012707 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12708 throw new IllegalArgumentException(
12709 "Invalid enterprise identifier in setProfileNetworkPreferences");
12710 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012711 final Set<UidRange> uidRangeSet =
12712 getUidListToBeAppliedForNetworkPreference(profile, preference);
12713 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12714 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12715 } else {
12716 throw new IllegalArgumentException(
12717 "Overlapping uid range in setProfileNetworkPreferences");
12718 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012719 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012720 nc.addEnterpriseId(
12721 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012722 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12723 break;
12724 default:
12725 throw new IllegalArgumentException(
12726 "Invalid preference in setProfileNetworkPreferences");
12727 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012728 preferenceList.add(new ProfileNetworkPreferenceInfo(
12729 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012730 if (hasDefaultPreference && preferenceList.size() > 1) {
12731 throw new IllegalArgumentException(
12732 "Default profile preference should not be set along with other preference");
12733 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012734 }
12735 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012736 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012737 }
12738
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012739 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12740 @NonNull final UserHandle profile,
12741 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12742 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012743 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12744 profileNetworkPreference.getIncludedUids());
12745
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012746 if (uidRangeSet.size() > 0) {
12747 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12748 throw new IllegalArgumentException(
12749 "Allow uid range is outside the uid range of profile.");
12750 }
12751 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012752 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012753 profileNetworkPreference.getExcludedUids());
12754 if (disallowUidRangeSet.size() > 0) {
12755 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12756 throw new IllegalArgumentException(
12757 "disallow uid range is outside the uid range of profile.");
12758 }
12759 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12760 disallowUidRangeSet);
12761 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012762 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012763 uidRangeSet.add(profileUids);
12764 }
12765 }
12766 return uidRangeSet;
12767 }
12768
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012769 private boolean isEnterpriseIdentifierValid(
12770 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012771 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012772 return true;
12773 }
12774 return false;
12775 }
12776
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012777 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012778 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012779 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012780 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012781 // The NRI for a user should contain the request for capabilities.
12782 // If fallback to default network is needed then NRI should include
12783 // the request for the default network. Create an image of it to
12784 // have the correct UIDs in it (also a request can only be part of one NRI, because
12785 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012786 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12787 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012788 if (pref.allowFallback) {
12789 nrs.add(createDefaultInternetRequestForTransport(
12790 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12791 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012792 if (VDBG) {
12793 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12794 pref.capabilities.getUids()));
12795 }
12796
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012797 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012798 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012799 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012800 result.add(nri);
12801 }
12802 return result;
12803 }
12804
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012805 /**
12806 * Compare if the given UID range sets have the same UIDs.
12807 *
12808 */
12809 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012810 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012811 @NonNull Set<UidRange> uidRangeSet) {
12812 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12813 return false;
12814 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012815 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012816 if (UidRangeUtils.doesRangeSetOverlap(
12817 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12818 return true;
12819 }
12820 }
12821 return false;
12822 }
12823
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012824 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012825 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012826 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012827 /*
12828 * handleSetProfileNetworkPreference is always called for single user.
12829 * preferenceList only contains preferences for different uids within the same user
12830 * (enforced by getUidListToBeAppliedForNetworkPreference).
12831 * Clear all the existing preferences for the user before applying new preferences.
12832 *
12833 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012834 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12835 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012836 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12837 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012838
paulhu74128522021-09-28 02:29:03 +000012839 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12840 addPerAppDefaultNetworkRequests(
12841 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012842 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012843
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012844 // Finally, rematch.
12845 rematchAllNetworksAndRequests();
12846
12847 if (null != listener) {
12848 try {
12849 listener.onComplete();
12850 } catch (RemoteException e) {
12851 loge("Listener for setProfileNetworkPreference has died");
12852 }
12853 }
12854 }
12855
paulhu51f77dc2021-06-07 02:34:20 +000012856 @VisibleForTesting
12857 @NonNull
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012858 ArraySet<NetworkRequestInfo> createNrisForPreferenceOrder(@NonNull final Set<Integer> uids,
12859 @NonNull final List<NetworkRequest> requests,
12860 final int preferenceOrder) {
paulhu51f77dc2021-06-07 02:34:20 +000012861 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12862 if (uids.size() == 0) {
12863 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12864 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
paulhu51f77dc2021-06-07 02:34:20 +000012865 return nris;
12866 }
12867
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012868 final Set<UidRange> ranges = new ArraySet<>();
12869 for (final int uid : uids) {
12870 ranges.add(new UidRange(uid, uid));
12871 }
12872 setNetworkRequestUids(requests, ranges);
12873 nris.add(new NetworkRequestInfo(Process.myUid(), requests, preferenceOrder));
12874 return nris;
12875 }
12876
12877 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12878 @NonNull final Set<Integer> uids) {
paulhu51f77dc2021-06-07 02:34:20 +000012879 final List<NetworkRequest> requests = new ArrayList<>();
12880 // The NRI should be comprised of two layers:
12881 // - The request for the mobile network preferred.
12882 // - The request for the default network, for fallback.
12883 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012884 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012885 requests.add(createDefaultInternetRequestForTransport(
12886 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012887 return createNrisForPreferenceOrder(uids, requests, PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED
12888 );
12889 }
12890
12891 ArraySet<NetworkRequestInfo> createMultiLayerNrisFromSatelliteNetworkFallbackUids(
12892 @NonNull final Set<Integer> uids) {
12893 final List<NetworkRequest> requests = new ArrayList<>();
12894
12895 // request: track default(unrestricted internet network)
12896 requests.add(createDefaultInternetRequestForTransport(
12897 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12898
12899 // request: restricted Satellite internet
12900 final NetworkCapabilities cap = new NetworkCapabilities.Builder()
12901 .addCapability(NET_CAPABILITY_INTERNET)
12902 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
12903 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED)
12904 .addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE)
12905 .build();
12906 requests.add(createNetworkRequest(NetworkRequest.Type.REQUEST, cap));
12907
12908 return createNrisForPreferenceOrder(uids, requests, PREFERENCE_ORDER_SATELLITE_FALLBACK);
paulhu51f77dc2021-06-07 02:34:20 +000012909 }
12910
12911 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012912 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012913 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12914 addPerAppDefaultNetworkRequests(
12915 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012916 // Finally, rematch.
12917 rematchAllNetworksAndRequests();
12918 }
12919
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012920 private void handleSetSatelliteNetworkPreference(
12921 @NonNull final Set<Integer> satelliteNetworkPreferredUids) {
12922 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_SATELLITE_FALLBACK);
12923 addPerAppDefaultNetworkRequests(
12924 createMultiLayerNrisFromSatelliteNetworkFallbackUids(satelliteNetworkPreferredUids)
12925 );
12926 // Finally, rematch.
12927 rematchAllNetworksAndRequests();
12928 }
12929
Patrick Rohr2857ac42022-01-21 14:58:16 +010012930 private void handleIngressRateLimitChanged() {
12931 final long oldIngressRateLimit = mIngressRateLimit;
12932 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12933 mContext);
12934 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12935 if (canNetworkBeRateLimited(networkAgent)) {
12936 // If rate limit has previously been enabled, remove the old limit first.
12937 if (oldIngressRateLimit >= 0) {
12938 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12939 }
12940 if (mIngressRateLimit >= 0) {
12941 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12942 mIngressRateLimit);
12943 }
12944 }
12945 }
12946 }
12947
12948 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012949 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012950 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012951
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012952 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12953 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12954 // internet connectivity can be rate limited.
12955 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12956 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012957 return false;
12958 }
12959
12960 final String iface = networkAgent.linkProperties.getInterfaceName();
12961 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012962 // This may happen in tests, but if there is no interface then there is nothing that
12963 // can be rate limited.
12964 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012965 return false;
12966 }
12967 return true;
12968 }
12969
James Mattis45d81842021-01-10 14:24:24 -080012970 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012971 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12972 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012973 }
12974
12975 /**
12976 * Used by automotive devices to set the network preferences used to direct traffic at an
12977 * application level as per the given OemNetworkPreferences. An example use-case would be an
12978 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12979 * vehicle via a particular network.
12980 *
12981 * Calling this will overwrite the existing preference.
12982 *
James Mattisda32cfe2021-01-26 16:23:52 -080012983 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012984 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012985 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012986 */
James Mattis47db0582021-01-01 14:13:35 -080012987 @Override
James Mattis45d81842021-01-10 14:24:24 -080012988 public void setOemNetworkPreference(
12989 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012990 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012991
James Mattisfa270db2021-05-31 17:11:10 -070012992 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12993 // Only bypass the permission/device checks if this is a valid test request.
12994 if (isValidTestOemNetworkPreference(preference)) {
12995 enforceManageTestNetworksPermission();
12996 } else {
12997 enforceAutomotiveDevice();
12998 enforceOemNetworkPreferencesPermission();
12999 validateOemNetworkPreferences(preference);
13000 }
James Mattis45d81842021-01-10 14:24:24 -080013001
James Mattis45d81842021-01-10 14:24:24 -080013002 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
13003 new Pair<>(preference, listener)));
13004 }
13005
James Mattisfa270db2021-05-31 17:11:10 -070013006 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000013007 * Sets the specified UIDs to get/receive the VPN as the only default network.
13008 *
13009 * Calling this will overwrite the existing network preference for this session, and the
13010 * specified UIDs won't get any default network when no VPN is connected.
13011 *
13012 * @param session The VPN session which manages the passed UIDs.
13013 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
13014 * setting for this session if the array is empty. Null is not allowed, the
13015 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
13016 * @hide
13017 */
13018 @Override
13019 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
13020 Objects.requireNonNull(ranges);
13021 enforceNetworkStackOrSettingsPermission();
13022 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
13023 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
13024 throw new IllegalArgumentException(
13025 "setVpnNetworkPreference: Passed UID ranges overlap");
13026 }
13027
13028 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
13029 new VpnNetworkPreferenceInfo(session,
13030 new ArraySet<UidRange>(Arrays.asList(ranges)))));
13031 }
13032
13033 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
13034 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
13035
13036 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
13037 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
13038
13039 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
13040 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
13041 // Finally, rematch.
13042 rematchAllNetworksAndRequests();
13043 }
13044
13045 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
13046 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
13047 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
13048 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
13049 final List<NetworkRequest> requests = new ArrayList<>();
13050 // Request VPN only, so other networks won't be the fallback options when VPN is not
13051 // connected temporarily.
13052 requests.add(createVpnRequest());
13053 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
13054 setNetworkRequestUids(requests, uidRanges);
13055 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
13056 }
13057 return nris;
13058 }
13059
13060 /**
James Mattisfa270db2021-05-31 17:11:10 -070013061 * Check the validity of an OEM network preference to be used for testing purposes.
13062 * @param preference the preference to validate
13063 * @return true if this is a valid OEM network preference test request.
13064 */
13065 private boolean isValidTestOemNetworkPreference(
13066 @NonNull final OemNetworkPreferences preference) {
13067 // Allow for clearing of an existing OemNetworkPreference used for testing.
13068 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
13069 // changes after this check is complete. This is an unlikely scenario as calling of this API
13070 // is controlled by the OEM therefore the added complexity is not worth adding given those
13071 // circumstances. That said, it is an edge case to be aware of hence this comment.
13072 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
13073 && isTestOemNetworkPreference(mOemNetworkPreferences);
13074 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
13075 }
13076
13077 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
13078 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
13079 return prefMap.size() == 1
13080 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
13081 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
13082 }
13083
James Mattis45d81842021-01-10 14:24:24 -080013084 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
13085 for (@OemNetworkPreferences.OemNetworkPreference final int pref
13086 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070013087 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
13088 throw new IllegalArgumentException(
13089 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
13090 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080013091 }
13092 }
13093 }
13094
13095 private void handleSetOemNetworkPreference(
13096 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090013097 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080013098 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
13099 if (DBG) {
13100 log("set OEM network preferences :" + preference.toString());
13101 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090013102
James Mattiscb1e0362021-04-06 17:07:42 -070013103 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000013104 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
13105 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
13106 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080013107 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080013108
13109 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090013110 try {
13111 listener.onComplete();
13112 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080013113 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090013114 }
James Mattis45d81842021-01-10 14:24:24 -080013115 }
13116 }
13117
paulhu74128522021-09-28 02:29:03 +000013118 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080013119 // Skip the requests which are set by other network preference. Because the uid range rules
13120 // should stay in netd.
13121 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080013122 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080013123 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080013124 }
13125
James Mattis3ce3d3c2021-02-09 18:18:28 -080013126 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
13127 ensureRunningOnConnectivityServiceThread();
13128 mDefaultNetworkRequests.addAll(nris);
13129 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
13130 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080013131 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000013132 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
13133 nrisToRegister.addAll(
13134 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
13135 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013136 }
13137
13138 /**
13139 * All current requests that are tracking the default network need to be assessed as to whether
13140 * or not the current set of per-application default requests will be changing their default
13141 * network. If so, those requests will need to be updated so that they will send callbacks for
13142 * default network changes at the appropriate time. Additionally, those requests tracking the
13143 * default that were previously updated by this flow will need to be reassessed.
13144 * @return the nris which will need to be updated.
13145 */
13146 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
13147 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
13148 // Get the distinct nris to check since for multilayer requests, it is possible to have the
13149 // same nri in the map's values for each of its NetworkRequest objects.
13150 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080013151 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013152 // Include this nri if it is currently being tracked.
13153 if (isPerAppTrackedNri(nri)) {
13154 defaultCallbackRequests.add(nri);
13155 continue;
13156 }
13157 // We only track callbacks for requests tracking the default.
13158 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
13159 continue;
13160 }
13161 // Include this nri if it will be tracked by the new per-app default requests.
13162 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013163 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080013164 if (isNriGoingToBeTracked) {
13165 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080013166 }
13167 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080013168 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080013169 }
13170
James Mattis3ce3d3c2021-02-09 18:18:28 -080013171 /**
13172 * Create nris for those network requests that are currently tracking the default network that
13173 * are being controlled by a per-application default.
13174 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
13175 * foundation when creating the nri. Important items include the calling uid's original
13176 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
13177 * requests are assumed to have already been validated as needing to be updated.
13178 * @return the Set of nris to use when registering network requests.
13179 */
13180 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
13181 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
13182 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
13183 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
13184 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013185 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013186
Chalard Jean9473c982021-07-29 20:03:04 +090013187 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080013188 if (trackingNri == mDefaultRequest) {
13189 callbackRequestsToRegister.add(new NetworkRequestInfo(
13190 callbackRequest,
13191 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
13192 continue;
13193 }
13194
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013195 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013196 callbackRequestsToRegister.add(new NetworkRequestInfo(
13197 callbackRequest,
13198 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013199 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090013200 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080013201 }
13202 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080013203 }
13204
Chalard Jean17215832021-03-01 14:06:28 +090013205 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
13206 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090013207 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000013208 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090013209 }
13210 }
13211
James Mattis45d81842021-01-10 14:24:24 -080013212 /**
13213 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
13214 */
13215 @VisibleForTesting
13216 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013217 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080013218 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013219 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080013220 final SparseArray<Set<Integer>> uids =
13221 createUidsFromOemNetworkPreferences(preference);
13222 for (int i = 0; i < uids.size(); i++) {
13223 final int key = uids.keyAt(i);
13224 final Set<Integer> value = uids.valueAt(i);
13225 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
13226 // No need to add an nri without any requests.
13227 if (0 == nri.mRequests.size()) {
13228 continue;
13229 }
13230 nris.add(nri);
13231 }
13232
13233 return nris;
13234 }
13235
13236 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
13237 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070013238 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080013239 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080013240 final List<UserHandle> users =
13241 mContext.getSystemService(UserManager.class).getUserHandles(true);
13242 if (null == users || users.size() == 0) {
13243 if (VDBG || DDBG) {
13244 log("No users currently available for setting the OEM network preference.");
13245 }
James Mattisb6b6a432021-06-01 22:30:36 -070013246 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080013247 }
James Mattis45d81842021-01-10 14:24:24 -080013248 for (final Map.Entry<String, Integer> entry :
13249 preference.getNetworkPreferences().entrySet()) {
13250 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070013251 // Add the rules for all users as this policy is device wide.
13252 for (final UserHandle user : users) {
13253 try {
13254 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
13255 if (!prefToUids.contains(pref)) {
13256 prefToUids.put(pref, new ArraySet<>());
13257 }
13258 prefToUids.get(pref).add(uid);
13259 } catch (PackageManager.NameNotFoundException e) {
13260 // Although this may seem like an error scenario, it is ok that uninstalled
13261 // packages are sent on a network preference as the system will watch for
13262 // package installations associated with this network preference and update
13263 // accordingly. This is done to minimize race conditions on app install.
13264 continue;
James Mattis45d81842021-01-10 14:24:24 -080013265 }
James Mattis45d81842021-01-10 14:24:24 -080013266 }
13267 }
James Mattisb6b6a432021-06-01 22:30:36 -070013268 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080013269 }
13270
13271 private NetworkRequestInfo createNriFromOemNetworkPreferences(
13272 @OemNetworkPreferences.OemNetworkPreference final int preference,
13273 @NonNull final Set<Integer> uids) {
13274 final List<NetworkRequest> requests = new ArrayList<>();
13275 // Requests will ultimately be evaluated by order of insertion therefore it matters.
13276 switch (preference) {
13277 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
13278 requests.add(createUnmeteredNetworkRequest());
13279 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070013280 requests.add(createDefaultInternetRequestForTransport(
13281 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080013282 break;
13283 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
13284 requests.add(createUnmeteredNetworkRequest());
13285 requests.add(createOemPaidNetworkRequest());
13286 break;
13287 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
13288 requests.add(createOemPaidNetworkRequest());
13289 break;
13290 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
13291 requests.add(createOemPrivateNetworkRequest());
13292 break;
James Mattisfa270db2021-05-31 17:11:10 -070013293 case OEM_NETWORK_PREFERENCE_TEST:
13294 requests.add(createUnmeteredNetworkRequest());
13295 requests.add(createTestNetworkRequest());
13296 requests.add(createDefaultRequest());
13297 break;
13298 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
13299 requests.add(createTestNetworkRequest());
13300 break;
James Mattis45d81842021-01-10 14:24:24 -080013301 default:
13302 // This should never happen.
13303 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
13304 + " called with invalid preference of " + preference);
13305 }
13306
James Mattisfa270db2021-05-31 17:11:10 -070013307 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090013308 for (final int uid : uids) {
13309 ranges.add(new UidRange(uid, uid));
13310 }
13311 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080013312 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080013313 }
13314
13315 private NetworkRequest createUnmeteredNetworkRequest() {
13316 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13317 .addCapability(NET_CAPABILITY_NOT_METERED)
13318 .addCapability(NET_CAPABILITY_VALIDATED);
13319 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
13320 }
13321
13322 private NetworkRequest createOemPaidNetworkRequest() {
13323 // NET_CAPABILITY_OEM_PAID is a restricted capability.
13324 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13325 .addCapability(NET_CAPABILITY_OEM_PAID)
13326 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13327 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13328 }
13329
13330 private NetworkRequest createOemPrivateNetworkRequest() {
13331 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
13332 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13333 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
13334 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13335 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13336 }
13337
13338 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070013339 final NetworkCapabilities netcap = new NetworkCapabilities();
13340 netcap.addCapability(NET_CAPABILITY_INTERNET);
13341 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
13342 return netcap;
13343 }
13344
13345 private NetworkRequest createTestNetworkRequest() {
13346 final NetworkCapabilities netcap = new NetworkCapabilities();
13347 netcap.clearAll();
13348 netcap.addTransportType(TRANSPORT_TEST);
13349 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080013350 }
James Mattis47db0582021-01-01 14:13:35 -080013351 }
markchien738ad912021-12-09 18:15:45 +080013352
Junyu Lai38c75032023-12-04 07:52:19 +000013353 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080013354 @Override
Junyu Laidf210362023-10-24 02:47:50 +000013355 public void setDataSaverEnabled(final boolean enable) {
13356 enforceNetworkStackOrSettingsPermission();
13357 try {
13358 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
13359 if (!ret) {
13360 throw new IllegalStateException("Error when changing iptables: " + enable);
13361 }
13362 } catch (RemoteException e) {
13363 // Lack of permission or binder errors.
13364 throw new IllegalStateException(e);
13365 }
Ken Chen24330172023-10-20 13:02:14 +080013366
13367 try {
13368 mBpfNetMaps.setDataSaverEnabled(enable);
13369 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13370 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13371 }
Junyu Laidf210362023-10-24 02:47:50 +000013372 }
13373
13374 @Override
markchien738ad912021-12-09 18:15:45 +080013375 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13376 enforceNetworkStackOrSettingsPermission();
13377
13378 try {
13379 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013380 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013381 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013382 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013383 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013384 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013385 throw new IllegalStateException(e);
13386 }
13387 }
13388
13389 @Override
13390 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13391 enforceNetworkStackOrSettingsPermission();
13392
13393 try {
13394 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013395 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013396 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013397 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013398 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013399 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013400 throw new IllegalStateException(e);
13401 }
13402 }
markchiene1561fa2021-12-09 22:00:56 +080013403
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013404 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13405 throws PackageManager.NameNotFoundException {
13406 final PackageManager pm = mContext.getPackageManager();
13407 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13408 if (appId < Process.FIRST_APPLICATION_UID) {
13409 throw new RuntimeException("Can't set package firewall rule for system app "
13410 + packageName + " with appId " + appId);
13411 }
13412 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13413 final int uid = uh.getUid(appId);
13414 setUidFirewallRule(chain, uid, rule);
13415 }
13416 return appId;
13417 }
13418
markchiene1561fa2021-12-09 22:00:56 +080013419 @Override
markchien3c04e662022-03-22 16:29:56 +080013420 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013421 enforceNetworkStackOrSettingsPermission();
13422
markchien3c04e662022-03-22 16:29:56 +080013423 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13424 int firewallRule = getFirewallRuleType(chain, rule);
13425
13426 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13427 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13428 }
13429
markchiene1561fa2021-12-09 22:00:56 +080013430 try {
markchien3c04e662022-03-22 16:29:56 +080013431 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013432 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013433 throw new IllegalStateException(e);
13434 }
13435 }
markchien98a6f952022-01-13 23:43:53 +080013436
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013437 private int getPackageFirewallRule(final int chain, final String packageName)
13438 throws PackageManager.NameNotFoundException {
13439 final PackageManager pm = mContext.getPackageManager();
13440 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13441 return getUidFirewallRule(chain, appId);
13442 }
13443
Motomu Utsumi900b8062023-01-19 16:16:49 +090013444 @Override
13445 public int getUidFirewallRule(final int chain, final int uid) {
13446 enforceNetworkStackOrSettingsPermission();
13447 return mBpfNetMaps.getUidRule(chain, uid);
13448 }
13449
markchien3c04e662022-03-22 16:29:56 +080013450 private int getFirewallRuleType(int chain, int rule) {
13451 final int defaultRule;
13452 switch (chain) {
13453 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013454 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13455 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013456 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013457 defaultRule = FIREWALL_RULE_ALLOW;
13458 break;
13459 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13460 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13461 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13462 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013463 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013464 defaultRule = FIREWALL_RULE_DENY;
13465 break;
13466 default:
13467 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13468 }
13469 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13470
13471 return rule;
13472 }
13473
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013474 private void closeSocketsForFirewallChainLocked(final int chain)
13475 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013476 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013477 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13478 // So, close all non-system socket owned by uids that are not explicitly allowed
13479 Set<Range<Integer>> ranges = new ArraySet<>();
13480 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13481 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13482 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13483 } else {
13484 // Denylist means the firewall allows all by default, uids must be explicitly denied
13485 // So, close socket owned by uids that are explicitly denied
13486 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13487 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13488 }
13489 }
13490
markchien98a6f952022-01-13 23:43:53 +080013491 @Override
13492 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13493 enforceNetworkStackOrSettingsPermission();
13494
13495 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013496 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013497 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013498 throw new IllegalStateException(e);
13499 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013500
Chalard Jeandf29a852023-05-29 17:02:43 +090013501 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013502 try {
13503 closeSocketsForFirewallChainLocked(chain);
13504 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13505 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13506 }
13507 }
markchien98a6f952022-01-13 23:43:53 +080013508 }
13509
markchien00a0bed2022-01-13 23:46:13 +080013510 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013511 public boolean getFirewallChainEnabled(final int chain) {
13512 enforceNetworkStackOrSettingsPermission();
13513
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013514 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013515 }
13516
13517 @Override
markchien00a0bed2022-01-13 23:46:13 +080013518 public void replaceFirewallChain(final int chain, final int[] uids) {
13519 enforceNetworkStackOrSettingsPermission();
13520
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013521 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013522 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013523
13524 @Override
13525 public IBinder getCompanionDeviceManagerProxyService() {
13526 enforceNetworkStackPermission(mContext);
13527 return mCdmps;
13528 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013529
13530 @Override
13531 public IBinder getRoutingCoordinatorService() {
13532 enforceNetworkStackPermission(mContext);
13533 return mRoutingCoordinatorService;
13534 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013535}