blob: e6287bc1c79634db4a58d312c0029f0c00a7d648 [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.CarrierPrivilegeAuthenticator.CarrierPrivilegesLostListener;
118import static com.android.server.connectivity.ConnectivityFlags.REQUEST_RESTRICTED_WIFI;
Chalard Jeaneb663892023-10-07 15:17:07 +0900119
Chalard Jean5b639762020-03-09 21:25:37 +0900120import android.Manifest;
Junyu Lai71b51532024-02-01 10:39:01 +0800121import android.annotation.CheckResult;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000122import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800123import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600124import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800125import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000126import android.app.ActivityManager;
127import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800128import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800129import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700130import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700131import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900132import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800133import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700134import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800135import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800136import android.content.ContentResolver;
137import android.content.Context;
138import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700139import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800140import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900141import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700142import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800143import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900144import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900145import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700146import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800147import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800148import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800149import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900150import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800151import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900152import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800153import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900154import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800155import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700156import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900157import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800158import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800159import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800160import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800161import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800162import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900163import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900164import android.net.INetworkMonitor;
165import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900166import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900167import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700168import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800169import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900170import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900171import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900172import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800173import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900174import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900175import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100176import android.net.MatchAllNetworkSpecifier;
Yang Sun29037f62023-12-04 10:31:58 +0800177import android.net.MulticastRoutingConfig;
Ken Chen6df7a902021-04-09 15:08:42 +0800178import android.net.NativeNetworkConfig;
179import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800180import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700181import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700182import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900183import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700184import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800185import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700186import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900187import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900188import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000189import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900190import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700191import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900192import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700193import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900194import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700195import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800196import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900197import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700198import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000199import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800200import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900201import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800202import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400203import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700204import android.net.QosCallbackException;
205import android.net.QosFilter;
206import android.net.QosSocketFilter;
207import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700208import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800209import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800210import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900211import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400212import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800213import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800214import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400215import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800216import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900217import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900218import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900219import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900220import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800221import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900222import android.net.networkstack.ModuleNetworkStackClient;
223import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900224import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800225import android.net.resolv.aidl.DnsHealthEventParcel;
226import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
227import android.net.resolv.aidl.Nat64PrefixEventParcel;
228import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900229import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900230import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800231import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800232import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800233import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700234import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000235import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800236import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700237import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700238import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800239import android.os.Looper;
240import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700241import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700242import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900243import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800244import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700245import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700246import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800247import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700248import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900249import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900250import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700251import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700252import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400253import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800254import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900255import android.stats.connectivity.MeteredState;
256import android.stats.connectivity.RequestType;
257import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900258import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700259import android.system.ErrnoException;
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;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000380import java.util.function.Consumer;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800381
382/**
383 * @hide
384 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800385public class ConnectivityService extends IConnectivityManager.Stub
386 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900387 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800388
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900389 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900390 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900391 private static final String NETWORK_ARG = "networks";
392 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800393 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900394
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900395 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900396 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
397 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800398
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900399 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700400
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100401 /**
402 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
403 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800404 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100405 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
406 * (preferably via runtime resource overlays).
407 */
408 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
409 "http://connectivitycheck.gstatic.com/generate_204";
410
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700411 // TODO: create better separation between radio types and network types
412
Robert Greenwalt2034b912009-08-12 16:08:25 -0700413 // how long to wait before switching back to a radio's default network
414 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
415 // system property that can override the above value
416 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
417 "android.telephony.apn-restore";
418
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900419 // How long to wait before putting up a "This network doesn't have an Internet connection,
420 // connect anyway?" dialog after the user selects a network that doesn't validate.
421 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
422
Chalard Jean5fb43c72022-09-08 19:03:14 +0900423 // How long to wait before considering that a network is bad in the absence of any form
424 // of connectivity (valid, partial, captive portal). If none has been detected after this
425 // delay, the stack considers this network bad, which may affect how it's handled in ranking
426 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900427 // Timeout in case the "actively prefer bad wifi" feature is on
428 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
429 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900430 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900431
junyulai0ac374f2020-12-14 18:41:52 +0800432 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900433 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
434 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800435 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700436
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800437 // Delimiter used when creating the broadcast delivery group for sending
438 // CONNECTIVITY_ACTION broadcast.
439 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
440
he_won.hwang881307a2022-03-15 21:23:52 +0900441 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900442 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900443
Daniel Brightf9e945b2020-06-15 16:10:01 -0700444 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900445 @VisibleForTesting
446 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700447
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900448 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700449 @VisibleForTesting
450 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900451
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900452 @VisibleForTesting
453 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800454 @VisibleForTesting
455 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900456 // True if the cell radio of the device is capable of time-sharing.
457 @VisibleForTesting
458 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900459
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800460 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800461 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800462 private final int mReleasePendingIntentDelayMs;
463
Chalard Jean46bfbf02022-02-02 00:56:25 +0900464 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900465
Motomu Utsumif360aa62023-01-30 17:52:20 +0900466 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700467
Chalard Jean9473c982021-07-29 20:03:04 +0900468 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800469 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700470 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800471 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700472
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900473 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700474
Ying Xu7cabd322024-01-15 18:40:15 -0800475 private final boolean mRequestRestrictedWifiEnabled;
476
junyulaif2c67e42018-08-07 19:50:45 +0800477 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000478 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
479 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800480 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900481 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800482
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900483 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900484 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000485 private final int mWakeUpMark;
486 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000487 // The Context is created for UserHandle.ALL.
488 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900489 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900490 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700491 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700492 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800493
Chenbo Feng15416292018-11-08 17:36:21 -0800494 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800495 protected IDnsResolver mDnsResolver;
496 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800497 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700498 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900499 private final NetworkStatsManager mStatsManager;
500 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800501 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700502
Benedict Wong493e04b2018-11-09 14:45:34 -0800503 /**
504 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
505 * instances.
506 */
507 @GuardedBy("mTNSLock")
508 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800509 private final CompanionDeviceManagerProxyService mCdmps;
Yang Sun29037f62023-12-04 10:31:58 +0800510 private final MulticastRoutingCoordinatorService mMulticastRoutingCoordinatorService;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900511 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800512
513 private final Object mTNSLock = new Object();
514
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700515 private String mCurrentTcpBufferSizes;
516
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900517 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000518 new Class[] {
519 ConnectivityService.class,
520 NetworkAgent.class,
521 NetworkAgentInfo.class,
522 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900523
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500524 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400525 // Tear down networks that have no chance (e.g. even if validated) of becoming
526 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500527 // all networks have been rematched against all NetworkRequests.
528 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400529 // Don't reap networks. This should be passed when some networks have not yet been
530 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500531 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900532 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500533
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900534 private enum UnneededFor {
535 LINGER, // Determine whether this network is unneeded and should be lingered.
536 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
537 }
538
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700539 /**
paulhuaa0743d2021-05-26 21:56:03 +0800540 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800541 * should have priority. The order is passed to netd which will use it together
542 * with UID ranges to generate the corresponding IP rule. This serves to
543 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800544 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800545 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000546 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800547 *
paulhu48291862021-07-14 14:53:57 +0800548 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
549 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800550 */
paulhu48291862021-07-14 14:53:57 +0800551 // Used when sending to netd to code for "no order".
552 static final int PREFERENCE_ORDER_NONE = 0;
553 // Order for requests that don't code for a per-app preference. As it is
554 // out of the valid range, the corresponding order should be
555 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800556 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800557 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800558 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800559 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
560 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800561 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800562 static final int PREFERENCE_ORDER_OEM = 10;
563 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800564 // See {@link #setProfileNetworkPreference}.
565 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800566 static final int PREFERENCE_ORDER_PROFILE = 20;
567 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800568 // better scores are connected.
569 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800570 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800571 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000572 // Order of setting satellite network preference fallback when default message application
573 // with role_sms role and android.permission.SATELLITE_COMMUNICATION permission detected
574 @VisibleForTesting
575 static final int PREFERENCE_ORDER_SATELLITE_FALLBACK = 40;
Chalard Jeane6c95272022-01-25 21:04:21 +0900576 // Preference order that signifies the network shouldn't be set as a default network for
577 // the UIDs, only give them access to it. TODO : replace this with a boolean
578 // in NativeUidRangeConfig
579 @VisibleForTesting
580 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
581 // Bound for the lowest valid preference order.
582 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800583
584 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700585 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700586 * from one net to another. Clear happens when we get a new
587 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
588 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700589 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700590 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700591
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700592 /**
593 * used internally to reload global proxy settings
594 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700595 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700596
Robert Greenwalt34848c02011-03-25 13:09:25 -0700597 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400598 * PAC manager has received new port.
599 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800600 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400601
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700602 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900603 * used internally when registering NetworkProviders
604 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700605 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900606 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700607
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700608 /**
609 * used internally when registering NetworkAgents
610 * obj = Messenger
611 */
612 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
613
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700614 /**
615 * used to add a network request
616 * includes a NetworkRequestInfo
617 */
618 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
619
620 /**
621 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900622 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700623 * cancel it.
624 * includes a NetworkRequestInfo
625 */
626 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
627
628 /**
629 * used to add a network listener - no request
630 * includes a NetworkRequestInfo
631 */
632 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
633
634 /**
635 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400636 * arg1 = UID of caller
637 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700638 */
639 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
640
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700641 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900642 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700643 * obj = Messenger
644 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900645 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700646
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700647 /**
648 * used internally to expire a wakelock when transitioning
649 * from one net to another. Expire happens when we fail to find
650 * a new network (typically after 1 minute) -
651 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
652 * a replacement network.
653 */
654 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
655
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700656 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800657 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400658 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800659 */
660 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
661
662 /**
663 * used to remove a pending intent and its associated network request.
664 * arg1 = UID of caller
665 * obj = PendingIntent
666 */
667 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
668
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900669 /**
670 * used to specify whether a network should be used even if unvalidated.
671 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
672 * arg2 = whether to remember this choice in the future (1 or 0)
673 * obj = network
674 */
675 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
676
677 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700678 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900679 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700680 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900681
Paul Jensenc8873fc2015-06-17 14:15:39 -0400682 /**
683 * used to add a network listener with a pending intent
684 * obj = NetworkRequestInfo
685 */
686 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
687
Hugo Benichid6b510a2017-04-06 17:22:18 +0900688 /**
689 * used to specify whether a network should not be penalized when it becomes unvalidated.
690 */
691 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
692
693 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700694 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900695 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700696 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900697
Erik Kline31b4a9e2018-01-11 21:07:29 +0900698 // Handle changes in Private DNS settings.
699 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
700
dalyk1720e542018-03-05 12:42:22 -0500701 // Handle private DNS validation status updates.
702 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
703
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900704 /**
705 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
706 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800707 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
708 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
709 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900710 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900711 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900712
713 /**
714 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
715 * config was resolved.
716 * obj = PrivateDnsConfig
717 * arg2 = netid
718 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900719 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900720
721 /**
722 * Request ConnectivityService display provisioning notification.
723 * arg1 = Whether to make the notification visible.
724 * arg2 = NetID.
725 * obj = Intent to be launched when notification selected by user, null if !arg1.
726 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900727 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900728
729 /**
lucaslin2240ef62019-03-12 13:08:03 +0800730 * Used to specify whether a network should be used even if connectivity is partial.
731 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
732 * false)
733 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
734 * obj = network
735 */
lucaslin444d43a2020-02-20 16:56:59 +0800736 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800737
738 /**
lucasline117e2e2019-10-22 18:27:33 +0800739 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
740 * Both of the arguments are bitmasks, and the value of bits come from
741 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900742 * arg1 = unused
743 * arg2 = netId
744 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800745 */
lucaslin444d43a2020-02-20 16:56:59 +0800746 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800747
748 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900749 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
750 * arg1 = unused
751 * arg2 = netId
752 * obj = captive portal data
753 */
lucaslin444d43a2020-02-20 16:56:59 +0800754 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900755
756 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900757 * Used by setRequireVpnForUids.
758 * arg1 = whether the specified UID ranges are required to use a VPN.
759 * obj = Array of UidRange objects.
760 */
761 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
762
763 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900764 * Used internally when setting the default networks for OemNetworkPreferences.
765 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800766 */
767 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
768
769 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800770 * Used to indicate the system default network becomes active.
771 */
772 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
773
774 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900775 * Used internally when setting a network preference for a user profile.
776 * obj = Pair<ProfileNetworkPreference, Listener>
777 */
778 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
779
780 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000781 * Event to specify that reasons for why an uid is blocked changed.
782 * arg1 = uid
783 * arg2 = blockedReasons
784 */
785 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
786
787 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900788 * Event to register a new network offer
789 * obj = NetworkOffer
790 */
791 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
792
793 /**
794 * Event to unregister an existing network offer
795 * obj = INetworkOfferCallback
796 */
797 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
798
799 /**
paulhu51f77dc2021-06-07 02:34:20 +0000800 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
801 */
802 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
803
804 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800805 * Event to set temporary allow bad wifi within a limited time to override
806 * {@code config_networkAvoidBadWifi}.
807 */
808 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
809
810 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100811 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
812 */
813 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
814
815 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900816 * The initial evaluation period is over for this network.
817 *
818 * If no form of connectivity has been found on this network (valid, partial, captive portal)
819 * then the stack will now consider it to have been determined bad.
820 */
821 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
822
823 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000824 * Used internally when the user does not want the network from captive portal app.
825 * obj = Network
826 */
827 private static final int EVENT_USER_DOES_NOT_WANT = 58;
828
829 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000830 * Event to set VPN as preferred network for specific apps.
831 * obj = VpnNetworkPreferenceInfo
832 */
833 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
834
835 /**
chiachangwange0192a72023-02-06 13:25:01 +0000836 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
837 */
838 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
839
840 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000841 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
842 */
843 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
844
845 /**
Ying Xu7cabd322024-01-15 18:40:15 -0800846 * Event to inform the ConnectivityService handler when a uid has lost carrier privileges.
847 */
848 private static final int EVENT_UID_CARRIER_PRIVILEGES_LOST = 62;
849
850 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900851 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
852 * should be shown.
853 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900854 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900855
856 /**
857 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
858 * should be hidden.
859 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900860 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900861
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800862 /**
863 * The maximum alive time to allow bad wifi configuration for testing.
864 */
865 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
866
Patrick Rohr2857ac42022-01-21 14:58:16 +0100867 /**
chiachangwange0192a72023-02-06 13:25:01 +0000868 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
869 * testing.
870 */
871 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
872
873 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100874 * The priority of the tc police rate limiter -- smaller value is higher priority.
875 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
876 */
877 private static final short TC_PRIO_POLICE = 1;
878
879 /**
880 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
881 */
882 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700883 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100884
Hugo Benichi47011212017-03-30 10:46:05 +0900885 private static String eventName(int what) {
886 return sMagicDecoderRing.get(what, Integer.toString(what));
887 }
888
paulhua10d8212020-11-10 15:32:56 +0800889 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900890 final DnsResolverServiceManager dsm = context.getSystemService(
891 DnsResolverServiceManager.class);
892 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800893 }
894
Cody Kesting73708bf2019-12-18 10:57:50 -0800895 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900896 @VisibleForTesting
897 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700898 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700899 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700900 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700901 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800902 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
903 @VisibleForTesting
904 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
905
Erik Kline32120082017-12-13 19:40:49 +0900906 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900907 @VisibleForTesting
908 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700909
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400910 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800911 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400912
Chalard Jean46bfbf02022-02-02 00:56:25 +0900913 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800914 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700915
Chalard Jean5d70ba42018-06-07 16:44:04 +0900916 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
917 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800918 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400919
Erik Kline05f2b402015-04-30 12:58:40 +0900920 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700921
Chalard Jean46bfbf02022-02-02 00:56:25 +0900922 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400923
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700924 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900925 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700926
Valentin Iftime9fa35092019-09-24 13:32:13 +0200927 private Set<String> mWolSupportedInterfaces;
928
Roshan Pius08c94fb2020-01-16 12:17:17 -0800929 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800930 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800931 private final AppOpsManager mAppOpsManager;
932
933 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400934
chiachangwang3d60bac2023-01-17 14:38:08 +0000935 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900936 private final QosCallbackTracker mQosCallbackTracker;
937 private final NetworkNotificationManager mNotifier;
938 private final LingerMonitor mLingerMonitor;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000939 private final SatelliteAccessController mSatelliteAccessController;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900940
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700941 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800942 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700943
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900944 // Sequence number for NetworkProvider IDs.
945 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
946 NetworkProvider.FIRST_PROVIDER_ID);
947
Erik Klineedf878b2015-07-09 18:24:03 +0900948 // NetworkRequest activity String log entries.
949 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
950 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
951
Hugo Benichid159fdd2016-07-11 11:05:12 +0900952 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900953 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900954 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
955
Hugo Benichi47011212017-03-30 10:46:05 +0900956 private static final int MAX_WAKELOCK_LOGS = 20;
957 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900958 private int mTotalWakelockAcquisitions = 0;
959 private int mTotalWakelockReleases = 0;
960 private long mTotalWakelockDurationMs = 0;
961 private long mMaxWakelockDurationMs = 0;
962 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900963
Hugo Benichi208c0102016-07-28 17:53:06 +0900964 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900965
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000966 @Nullable private final NetworkRequestStateStatsMetrics mNetworkRequestStateStatsMetrics;
967
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700968 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900969 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700970
Erik Kline95ecfee2016-10-02 18:02:14 +0900971 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900972 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900973
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900974 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800975 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
976 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800977
Patrick Rohr2857ac42022-01-21 14:58:16 +0100978 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
979 // configured via {@link
980 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
981 // Only the handler thread is allowed to access this field.
982 private long mIngressRateLimit = -1;
983
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900984 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
985 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900986 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900987 @GuardedBy("mSelfCertifiedCapabilityCache")
988 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
989 mSelfCertifiedCapabilityCache = new HashMap<>();
990
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900991 // Flag to enable the feature of closing frozen app sockets.
992 private final boolean mDestroyFrozenSockets;
993
994 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
995 private final boolean mDelayDestroyFrozenSockets;
996
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900997 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
998 private final boolean mAllowSysUiConnectivityReports;
999
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001000 // Uids that ConnectivityService is pending to close sockets of.
1001 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
1002
Robert Greenwalt802c1102014-06-02 15:32:02 -07001003 /**
1004 * Implements support for the legacy "one network per network type" model.
1005 *
1006 * We used to have a static array of NetworkStateTrackers, one for each
1007 * network type, but that doesn't work any more now that we can have,
1008 * for example, more that one wifi network. This class stores all the
1009 * NetworkAgentInfo objects that support a given type, but the legacy
1010 * API will only see the first one.
1011 *
1012 * It serves two main purposes:
1013 *
1014 * 1. Provide information about "the network for a given type" (since this
1015 * API only supports one).
1016 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
1017 * the first network for a given type changes, or if the default network
1018 * changes.
1019 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001020 @VisibleForTesting
1021 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001022
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09001023 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001024 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001025
Robert Greenwalt802c1102014-06-02 15:32:02 -07001026 /**
1027 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1028 * Each list holds references to all NetworkAgentInfos that are used to
1029 * satisfy requests for that network type.
1030 *
1031 * This array is built out at startup such that an unsupported network
1032 * doesn't get an ArrayList instance, making this a tristate:
1033 * unsupported, supported but not active and active.
1034 *
1035 * The actual lists are populated when we scan the network types that
1036 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001037 *
1038 * Threading model:
1039 * - addSupportedType() is only called in the constructor
1040 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1041 * They are therefore not thread-safe with respect to each other.
1042 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1043 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001044 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001045 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001046 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001047 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001048 @NonNull
1049 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001050
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001051 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1052 // an entry have no timer (equivalent to -1). Lazily loaded.
1053 @NonNull
1054 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1055
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001056 LegacyTypeTracker(@NonNull ConnectivityService service) {
1057 mService = service;
1058 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001059 }
1060
Chiachang Wang3bc52762021-11-25 14:17:57 +08001061 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1062 // addressed.
1063 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001064 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1065 final PackageManager pm = ctx.getPackageManager();
1066 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1067 addSupportedType(TYPE_WIFI);
1068 }
1069 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1070 addSupportedType(TYPE_WIFI_P2P);
1071 }
1072 if (tm.isDataCapable()) {
1073 // Telephony does not have granular support for these types: they are either all
1074 // supported, or none is supported
1075 addSupportedType(TYPE_MOBILE);
1076 addSupportedType(TYPE_MOBILE_MMS);
1077 addSupportedType(TYPE_MOBILE_SUPL);
1078 addSupportedType(TYPE_MOBILE_DUN);
1079 addSupportedType(TYPE_MOBILE_HIPRI);
1080 addSupportedType(TYPE_MOBILE_FOTA);
1081 addSupportedType(TYPE_MOBILE_IMS);
1082 addSupportedType(TYPE_MOBILE_CBS);
1083 addSupportedType(TYPE_MOBILE_IA);
1084 addSupportedType(TYPE_MOBILE_EMERGENCY);
1085 }
1086 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1087 addSupportedType(TYPE_BLUETOOTH);
1088 }
1089 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1090 // TYPE_PROXY is only used on Wear
1091 addSupportedType(TYPE_PROXY);
1092 }
1093 // Ethernet is often not specified in the configs, although many devices can use it via
1094 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001095 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001096 addSupportedType(TYPE_ETHERNET);
1097 }
1098
1099 // Always add TYPE_VPN as a supported type
1100 addSupportedType(TYPE_VPN);
1101 }
1102
1103 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001104 if (mTypeLists[type] != null) {
1105 throw new IllegalStateException(
1106 "legacy list for type " + type + "already initialized");
1107 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001108 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001109 }
1110
Robert Greenwalt802c1102014-06-02 15:32:02 -07001111 public boolean isTypeSupported(int type) {
1112 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1113 }
1114
1115 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001116 synchronized (mTypeLists) {
1117 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1118 return mTypeLists[type].get(0);
1119 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001120 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001121 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001122 }
1123
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001124 public int getRestoreTimerForType(int type) {
1125 synchronized (mTypeLists) {
1126 if (mRestoreTimers == null) {
1127 mRestoreTimers = loadRestoreTimers();
1128 }
1129 return mRestoreTimers.getOrDefault(type, -1);
1130 }
1131 }
1132
1133 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1134 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001135 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001136 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1137 for (final String config : configs) {
1138 final String[] splits = TextUtils.split(config, ",");
1139 if (splits.length != 2) {
1140 logwtf("Invalid restore timer token count: " + config);
1141 continue;
1142 }
1143 try {
1144 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1145 } catch (NumberFormatException e) {
1146 logwtf("Invalid restore timer number format: " + config, e);
1147 }
1148 }
1149 return ret;
1150 }
1151
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001152 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001153 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001154 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001155 log("Sending " + state
1156 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001157 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001158 }
1159 }
1160
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001161 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1162 // network type, to preserve previous behaviour.
1163 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1164 if (vpnNai != mService.getLegacyLockdownNai()) return;
1165
1166 if (vpnNai.declaredUnderlyingNetworks == null
1167 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1168 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1169 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1170 return;
1171 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001172 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001173 vpnNai.declaredUnderlyingNetworks[0]);
1174 if (underlyingNai == null) return;
1175
1176 final int type = underlyingNai.networkInfo.getType();
1177 final DetailedState state = DetailedState.CONNECTED;
1178 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1179 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1180 }
1181
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001182 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001183 public void add(int type, NetworkAgentInfo nai) {
1184 if (!isTypeSupported(type)) {
1185 return; // Invalid network type.
1186 }
1187 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1188
1189 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1190 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001191 return;
1192 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001193 synchronized (mTypeLists) {
1194 list.add(nai);
1195 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001196
Chalard Jean5b409c72021-02-04 13:12:59 +09001197 // Send a broadcast if this is the first network of its type or if it's the default.
1198 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001199
1200 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1201 // to preserve previous behaviour.
1202 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001203 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001204 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1205 mService.sendLegacyNetworkBroadcast(nai, state, type);
1206 }
1207
1208 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1209 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001210 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001211 }
1212
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001213 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001214 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001215 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1216 if (list == null || list.isEmpty()) {
1217 return;
1218 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001219 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001220
Hugo Benichi389633f2016-06-21 09:48:07 +09001221 synchronized (mTypeLists) {
1222 if (!list.remove(nai)) {
1223 return;
1224 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001225 }
1226
Lorenzo Colitti49767722015-05-01 00:30:10 +09001227 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001228 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1229 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001230 }
1231
1232 if (!list.isEmpty() && wasFirstNetwork) {
1233 if (DBG) log("Other network available for type " + type +
1234 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001235 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001236 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001237 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001238 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001239 }
1240 }
1241
1242 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001243 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1244 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001245 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001246 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001247 }
1248 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001249
Chalard Jean46bfbf02022-02-02 00:56:25 +09001250 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001251 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001252 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001253 final DetailedState state = nai.networkInfo.getDetailedState();
1254 for (int type = 0; type < mTypeLists.length; type++) {
1255 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001256 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001257 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001258 if (isFirst || contains && isDefault) {
1259 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001260 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001261 }
1262 }
1263 }
1264
Robert Greenwalt94e22142014-07-30 16:31:24 -07001265 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001266 pw.println("mLegacyTypeTracker:");
1267 pw.increaseIndent();
1268 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001269 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001270 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001271 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001272 pw.println();
1273 pw.println("Current state:");
1274 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001275 synchronized (mTypeLists) {
1276 for (int type = 0; type < mTypeLists.length; type++) {
1277 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1278 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001279 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001280 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001281 }
1282 }
1283 pw.decreaseIndent();
1284 pw.decreaseIndent();
1285 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001286 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001287 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001288 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001289
Ying Xu7cabd322024-01-15 18:40:15 -08001290 private final CarrierPrivilegesLostListenerImpl mCarrierPrivilegesLostListenerImpl =
1291 new CarrierPrivilegesLostListenerImpl();
1292
1293 private class CarrierPrivilegesLostListenerImpl implements CarrierPrivilegesLostListener {
1294 @Override
1295 public void onCarrierPrivilegesLost(int uid) {
1296 if (mRequestRestrictedWifiEnabled) {
1297 mHandler.sendMessage(mHandler.obtainMessage(
1298 EVENT_UID_CARRIER_PRIVILEGES_LOST, uid, 0 /* arg2 */));
1299 }
1300 }
1301 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001302 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001303 /**
1304 * Helper class which parses out priority arguments and dumps sections according to their
1305 * priority. If priority arguments are omitted, function calls the legacy dump command.
1306 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001307 private class LocalPriorityDump {
1308 private static final String PRIORITY_ARG = "--dump-priority";
1309 private static final String PRIORITY_ARG_HIGH = "HIGH";
1310 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001311 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001312
1313 LocalPriorityDump() {}
1314
1315 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001316 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> {
Junyu Laif8dba342023-10-12 17:01:03 +08001317 doDump(fd, pw, new String[]{DIAG_ARG});
1318 doDump(fd, pw, new String[]{SHORT_ARG});
1319 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1320 pw.println("dumpHigh timeout");
1321 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001322 }
1323
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001324 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001325 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> doDump(fd, pw, args),
Junyu Laif8dba342023-10-12 17:01:03 +08001326 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1327 pw.println("dumpNormal timeout");
1328 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001329 }
1330
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001331 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1332 if (args == null) {
1333 dumpNormal(fd, pw, args);
1334 return;
1335 }
1336
1337 String priority = null;
1338 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1339 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1340 argIndex++;
1341 priority = args[argIndex];
1342 }
1343 }
1344
1345 if (PRIORITY_ARG_HIGH.equals(priority)) {
1346 dumpHigh(fd, pw);
1347 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1348 dumpNormal(fd, pw, args);
1349 } else {
1350 // ConnectivityService publishes binder service using publishBinderService() with
1351 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001352 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1353 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001354 // TODO: Integrate into signal dump.
1355 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001356 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001357 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001358 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001359
Ying Xu7cabd322024-01-15 18:40:15 -08001360 @VisibleForTesting
1361 CarrierPrivilegesLostListener getCarrierPrivilegesLostListener() {
1362 return mCarrierPrivilegesLostListenerImpl;
1363 }
1364
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001365 /**
1366 * Dependencies of ConnectivityService, for injection in tests.
1367 */
1368 @VisibleForTesting
1369 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001370 public int getCallingUid() {
1371 return Binder.getCallingUid();
1372 }
1373
Chalard Jeandf29a852023-05-29 17:02:43 +09001374 public boolean isAtLeastS() {
1375 return SdkLevel.isAtLeastS();
1376 }
1377
1378 public boolean isAtLeastT() {
1379 return SdkLevel.isAtLeastT();
1380 }
1381
1382 public boolean isAtLeastU() {
1383 return SdkLevel.isAtLeastU();
1384 }
1385
Chalard Jeaneb663892023-10-07 15:17:07 +09001386 public boolean isAtLeastV() {
1387 return SdkLevel.isAtLeastV();
1388 }
1389
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001390 /**
1391 * Get system properties to use in ConnectivityService.
1392 */
1393 public MockableSystemProperties getSystemProperties() {
1394 return new MockableSystemProperties();
1395 }
1396
1397 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001398 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1399 */
1400 public ConnectivityResources getResources(@NonNull Context ctx) {
1401 return new ConnectivityResources(ctx);
1402 }
1403
1404 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001405 * Create a HandlerThread to use in ConnectivityService.
1406 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001407 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1408 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001409 }
1410
1411 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001412 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001413 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001414 public NetworkStackClientBase getNetworkStack() {
1415 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001416 }
1417
1418 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001419 * @see ProxyTracker
1420 */
1421 public ProxyTracker makeProxyTracker(@NonNull Context context,
1422 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001423 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001424 }
1425
1426 /**
1427 * @see NetIdManager
1428 */
1429 public NetIdManager makeNetIdManager() {
1430 return new NetIdManager();
1431 }
1432
1433 /**
1434 * @see NetworkUtils#queryUserAccess(int, int)
1435 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001436 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1437 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001438 }
1439
1440 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001441 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1442 * requires CAP_NET_ADMIN, which the unit tests do not have.
1443 */
1444 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1445 InetSocketAddress remote) {
1446 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1447 }
1448
1449 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001450 * @see MultinetworkPolicyTracker
1451 */
1452 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1453 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1454 return new MultinetworkPolicyTracker(c, h, r);
1455 }
1456
Aaron Huang330a4c02020-10-27 03:36:19 +08001457 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001458 * @see AutomaticOnOffKeepaliveTracker
1459 */
1460 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1461 @NonNull Context c, @NonNull Handler h) {
1462 return new AutomaticOnOffKeepaliveTracker(c, h);
1463 }
1464
Yang Sun29037f62023-12-04 10:31:58 +08001465 public MulticastRoutingCoordinatorService makeMulticastRoutingCoordinatorService(
1466 @NonNull Handler h) {
1467 try {
1468 return new MulticastRoutingCoordinatorService(h);
1469 } catch (UnsupportedOperationException e) {
1470 // Multicast routing is not supported by the kernel
1471 Log.i(TAG, "Skipping unsupported MulticastRoutingCoordinatorService");
1472 return null;
1473 }
1474 }
1475
chiachangwang7c17c282023-02-02 05:58:59 +00001476 /**
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001477 * @see NetworkRequestStateStatsMetrics
1478 */
1479 public NetworkRequestStateStatsMetrics makeNetworkRequestStateStatsMetrics(
1480 Context context) {
1481 // We currently have network requests metric for Watch devices only
1482 if (context.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
1483 return new NetworkRequestStateStatsMetrics();
1484 } else {
1485 return null;
1486 }
1487 }
1488
1489 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001490 * @see BatteryStatsManager
1491 */
1492 public void reportNetworkInterfaceForTransports(Context context, String iface,
1493 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001494 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001495 context.getSystemService(BatteryStatsManager.class);
1496 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1497 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001498
1499 public boolean getCellular464XlatEnabled() {
1500 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1501 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001502
1503 /**
1504 * @see PendingIntent#intentFilterEquals
1505 */
1506 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1507 return a.intentFilterEquals(b);
1508 }
1509
1510 /**
1511 * @see LocationPermissionChecker
1512 */
1513 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1514 return new LocationPermissionChecker(context);
1515 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001516
1517 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001518 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001519 *
1520 * This method returns null in versions before T, where carrier privilege
1521 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001522 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001523 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001524 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
Ying Xu7cabd322024-01-15 18:40:15 -08001525 @NonNull final Context context,
1526 @NonNull final TelephonyManager tm,
1527 boolean requestRestrictedWifiEnabled,
1528 @NonNull CarrierPrivilegesLostListener listener) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001529 if (isAtLeastT()) {
Ying Xu7cabd322024-01-15 18:40:15 -08001530 return new CarrierPrivilegeAuthenticator(
1531 context, tm, requestRestrictedWifiEnabled, listener);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001532 } else {
1533 return null;
1534 }
1535 }
1536
1537 /**
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00001538 * @see SatelliteAccessController
1539 */
1540 @Nullable
1541 public SatelliteAccessController makeSatelliteAccessController(
1542 @NonNull final Context context,
1543 Consumer<Set<Integer>> updateSatelliteNetworkFallbackUidCallback,
1544 @NonNull final Handler connectivityServiceInternalHandler) {
1545 return new SatelliteAccessController(context, updateSatelliteNetworkFallbackUidCallback,
1546 connectivityServiceInternalHandler);
1547 }
1548
1549 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001550 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001551 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001552 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001553 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001554 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001555
1556 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001557 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1558 */
1559 public boolean isFeatureNotChickenedOut(Context context, String name) {
1560 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1561 }
1562
1563 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001564 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001565 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001566 * @return BpfNetMaps implementation.
1567 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001568 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1569 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001570 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001571
1572 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001573 * @see ClatCoordinator
1574 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001575 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001576 public ClatCoordinator getClatCoordinator(INetd netd) {
1577 return new ClatCoordinator(
1578 new ClatCoordinator.Dependencies() {
1579 @NonNull
1580 public INetd getNetd() {
1581 return netd;
1582 }
1583 });
1584 }
1585
1586 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001587 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1588 */
1589 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1590 final InterfaceParams params = InterfaceParams.getByName(iface);
1591 if (params == null) {
1592 // the interface might have disappeared.
1593 logw("Failed to get interface params for interface " + iface);
1594 return;
1595 }
1596 try {
1597 // converting rateInBytesPerSecond from long to int is safe here because the
1598 // setting's range is limited to INT_MAX.
1599 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001600 Log.i(TAG,
1601 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001602 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1603 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1604 } catch (IOException e) {
1605 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1606 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1607 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1608 + ") failure: ", e);
1609 }
1610 }
1611
1612 /**
1613 * Wraps {@link TcUtils#tcFilterDelDev}
1614 */
1615 public void disableIngressRateLimit(String iface) {
1616 final InterfaceParams params = InterfaceParams.getByName(iface);
1617 if (params == null) {
1618 // the interface might have disappeared.
1619 logw("Failed to get interface params for interface " + iface);
1620 return;
1621 }
1622 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001623 Log.i(TAG,
1624 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001625 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1626 } catch (IOException e) {
1627 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1628 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1629 }
1630 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001631
1632 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001633 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1634 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001635 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001636 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001637 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001638 }
1639
1640 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001641 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1642 */
1643 // TODO: when available in all active branches:
1644 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1645 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1646 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1647 return BroadcastOptionsShimImpl.newInstance(options);
1648 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001649
1650 /**
1651 * Wrapper method for
1652 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1653 *
1654 * @param changeId The ID of the compatibility change in question.
1655 * @param packageName The package name of the app in question.
1656 * @param user The user that the operation is done for.
1657 * @return {@code true} if the change is enabled for the specified package.
1658 */
1659 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1660 @NonNull final UserHandle user) {
1661 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1662 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001663
1664 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001665 * As above but with a UID.
1666 * @see CompatChanges#isChangeEnabled(long, int)
1667 */
1668 public boolean isChangeEnabled(final long changeId, final int uid) {
1669 return CompatChanges.isChangeEnabled(changeId, uid);
1670 }
1671
1672 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001673 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1674 *
1675 * @param ranges target uid ranges
1676 * @param exemptUids uids to skip close socket
1677 */
1678 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1679 @NonNull final Set<Integer> exemptUids)
1680 throws SocketException, InterruptedIOException, ErrnoException {
1681 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1682 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001683
1684 /**
1685 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1686 *
1687 * @param ownerUids target uids to close sockets
1688 */
1689 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1690 throws SocketException, InterruptedIOException, ErrnoException {
1691 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1692 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001693
1694 /**
1695 * Schedule the evaluation timeout.
1696 *
1697 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1698 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1699 * of these events happen, this time will run out, after which the network is considered
1700 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1701 * on this network and considers it won't provide connectivity. In particular, that means
1702 * it's when the system prefers it to cell if it's wifi and configuration says it should
1703 * prefer bad wifi to cell.
1704 */
1705 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1706 @NonNull final Network network, final long delayMs) {
1707 handler.sendMessageDelayed(
1708 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1709 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001710 }
1711
junyulaie7c7d2a2021-01-26 15:29:15 +08001712 public ConnectivityService(Context context) {
1713 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001714 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1715 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001716 }
1717
1718 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001719 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1720 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001721 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001722
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001723 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001724 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001725 mSystemProperties = mDeps.getSystemProperties();
1726 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001727 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001728 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001729 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1730 // Pass limit - 1 to maintain backward compatibility.
1731 // TODO: Remove the workaround.
1732 mNetworkRequestCounter =
1733 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1734 mSystemNetworkRequestCounter =
1735 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001736
Hugo Benichi208c0102016-07-28 17:53:06 +09001737 mMetricsLog = logger;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001738 mNetworkRequestStateStatsMetrics = mDeps.makeNetworkRequestStateStatsMetrics(mContext);
James Mattis45d81842021-01-10 14:24:24 -08001739 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1740 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001741 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001742 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001743 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001744 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1745 mDefaultNetworkRequests.add(mDefaultRequest);
1746 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001747
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001748 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001749 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001750
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001751 // The default WiFi request is a background request so that apps using WiFi are
1752 // migrated to a better network (typically ethernet) when one comes up, instead
1753 // of staying on WiFi forever.
1754 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1755 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1756
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001757 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1758 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1759 NetworkRequest.Type.BACKGROUND_REQUEST);
1760
Chalard Jean0702f982021-09-16 21:50:07 +09001761 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1762 // TODO: Consider making the timer customizable.
1763 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1764 mCellularRadioTimesharingCapable =
1765 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1766
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001767 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1768 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1769
1770 if (SdkLevel.isAtLeastU()) {
1771 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1772 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1773 final int defaultUMarkMask = 0x80000000; // u32
1774
1775 if ((mark == 0) || (mask == 0)) {
1776 // simply treat unset/disabled as the default U value
1777 mark = defaultUMarkMask;
1778 mask = defaultUMarkMask;
1779 }
1780 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1781 // invalid device overlay settings
1782 throw new IllegalArgumentException(
1783 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1784 }
1785 }
1786
1787 mWakeUpMark = mark;
1788 mWakeUpMask = mask;
1789
Paul Hu51f816b2022-08-11 14:43:47 +00001790 mNetd = netd;
1791 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09001792 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00001793 mPermissionMonitor =
1794 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001795 mHandlerThread.start();
1796 mHandler = new InternalHandler(mHandlerThread.getLooper());
1797 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001798 mConnectivityDiagnosticsHandler =
1799 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001800
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001801 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001802 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001803
junyulaie7c7d2a2021-01-26 15:29:15 +08001804 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001805 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001806 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001807 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001808
Wink Saville32506bc2013-06-29 21:10:57 -07001809 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001810 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001811 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Ying Xu7cabd322024-01-15 18:40:15 -08001812 mRequestRestrictedWifiEnabled = mDeps.isAtLeastU()
1813 && mDeps.isFeatureEnabled(context, REQUEST_RESTRICTED_WIFI);
1814 mCarrierPrivilegeAuthenticator = mDeps.makeCarrierPrivilegeAuthenticator(
1815 mContext, mTelephonyManager, mRequestRestrictedWifiEnabled,
1816 mCarrierPrivilegesLostListenerImpl);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001817
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00001818 if (mDeps.isAtLeastU()
1819 && mDeps
1820 .isFeatureNotChickenedOut(mContext, ALLOW_SATALLITE_NETWORK_FALLBACK)) {
1821 mSatelliteAccessController = mDeps.makeSatelliteAccessController(
1822 mContext, this::updateSatelliteNetworkPreferenceUids, mHandler);
1823 } else {
1824 mSatelliteAccessController = null;
1825 }
1826
Sudheer Shanka9967d462021-03-18 19:09:25 +00001827 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001828 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1829 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001830 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001831
1832 final PowerManager powerManager = (PowerManager) context.getSystemService(
1833 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001834 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001835 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001836
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001837 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1838 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001839 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001840 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001841 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001842 mProtectedNetworks.add(p);
1843 } else {
1844 if (DBG) loge("Ignoring protectedNetwork " + p);
1845 }
1846 }
1847
soma, kawata29444ae2019-05-23 09:30:40 +09001848 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1849
James Mattis02220e22021-03-13 19:27:21 -08001850 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001851 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001852 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001853 final IntentFilter userIntentFilter = new IntentFilter();
1854 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1855 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1856 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1857 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001858
James Mattis02220e22021-03-13 19:27:21 -08001859 // Listen to package add/removes for netd
1860 final IntentFilter packageIntentFilter = new IntentFilter();
1861 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1862 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1863 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1864 packageIntentFilter.addDataScheme("package");
1865 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001866 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001867
Junyu Lai38c75032023-12-04 07:52:19 +00001868 // This is needed for pre-V devices to propagate the data saver status
1869 // to the BPF map. This isn't supported before Android T because BPF maps are
1870 // unsupported, and it's also unnecessary on Android V and later versions,
1871 // as the platform code handles data saver bit updates. Additionally, checking
1872 // the initial data saver status here is superfluous because the intent won't
1873 // be sent until the system is ready.
1874 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
1875 final IntentFilter dataSaverIntentFilter =
1876 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
1877 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
1878 null /* broadcastPermission */, mHandler);
1879 }
1880
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001881 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1882 // But reading the trunk stable flags from mainline modules is not supported yet.
1883 // So enabling this feature on V+ release.
1884 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1885 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1886 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001887
Chalard Jean46bfbf02022-02-02 00:56:25 +09001888 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001889 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001890 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001891 } catch (RemoteException | ServiceSpecificException e) {
1892 loge("Error registering event listener :" + e);
1893 }
1894
Erik Kline05f2b402015-04-30 12:58:40 +09001895 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1896 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001897
chiachangwang7c17c282023-02-02 05:58:59 +00001898 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001899 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001900 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001901
1902 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001903 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001904 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1905 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001906 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001907 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1908 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001909
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001910 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001911 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001912 mNetworkRanker =
1913 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1914
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001915 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001916
Chiachang Wangc1215d32020-10-20 15:38:58 +08001917 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001918 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001919
Chalard Jean28018572020-12-21 18:36:52 +09001920 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1921 // request that doesn't allow fallback to the default network. It should never be visible
1922 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1923 // arguments like the handler or the DnsResolver.
1924 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001925 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001926 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001927 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001928 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001929 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001930 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1931 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001932
1933 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001934 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1935 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1936 // Even if it could, running on S would at least require mocking out the BPF map,
1937 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1938 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001939 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001940 mDscpPolicyTracker = new DscpPolicyTracker();
1941 }
Tyler Wear72388212021-09-09 14:49:02 -07001942 } catch (ErrnoException e) {
1943 loge("Unable to create DscpPolicyTracker");
1944 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001945
1946 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1947 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001948
Chalard Jeandf29a852023-05-29 17:02:43 +09001949 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001950 mCdmps = new CompanionDeviceManagerProxyService(context);
1951 } else {
1952 mCdmps = null;
1953 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001954
Chalard Jean2fb66f12023-08-25 12:50:37 +09001955 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
Yang Sun29037f62023-12-04 10:31:58 +08001956 mMulticastRoutingCoordinatorService =
1957 mDeps.makeMulticastRoutingCoordinatorService(mHandler);
Chalard Jean2fb66f12023-08-25 12:50:37 +09001958
Motomu Utsumi701efff2024-02-13 12:46:59 +09001959 mDestroyFrozenSockets = mDeps.isAtLeastV() || (mDeps.isAtLeastU()
1960 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION));
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001961 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1962 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001963 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1964 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001965 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001966 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1967 new UidFrozenStateChangedCallback() {
1968 @Override
1969 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1970 if (uids.length != frozenStates.length) {
1971 Log.wtf(TAG, "uids has length " + uids.length
1972 + " but frozenStates has length " + frozenStates.length);
1973 return;
1974 }
1975
1976 final UidFrozenStateChangedArgs args =
1977 new UidFrozenStateChangedArgs(uids, frozenStates);
1978
1979 mHandler.sendMessage(
1980 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1981 }
1982 };
1983
1984 final ActivityManager activityManager =
1985 mContext.getSystemService(ActivityManager.class);
1986 activityManager.registerUidFrozenStateChangedCallback(
1987 (Runnable r) -> r.run(), frozenStateChangedCallback);
1988 }
Yuyang Huang41557552023-11-28 12:47:22 +09001989
1990 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
1991 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
1992 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001993 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001994
Xiao Ma0a171c02022-01-23 16:14:51 +00001995 /**
1996 * Check whether or not the device supports Ethernet transport.
1997 */
1998 public static boolean deviceSupportsEthernet(final Context context) {
1999 final PackageManager pm = context.getPackageManager();
2000 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
2001 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
2002 }
2003
Chalard Jean46adcf32018-04-18 20:18:38 +09002004 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002005 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
2006 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09002007 }
2008
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002009 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
2010 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09002011 final NetworkCapabilities netCap = new NetworkCapabilities();
2012 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002013 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09002014 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002015 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09002016 return netCap;
2017 }
2018
James Mattis45d81842021-01-10 14:24:24 -08002019 private NetworkRequest createDefaultRequest() {
2020 return createDefaultInternetRequestForTransport(
2021 TYPE_NONE, NetworkRequest.Type.REQUEST);
2022 }
2023
lucaslin3ba7cc22022-12-19 02:35:33 +00002024 private NetworkRequest createVpnRequest() {
2025 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
2026 .withoutDefaultCapabilities()
2027 .addTransportType(TRANSPORT_VPN)
2028 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
2029 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
2030 .build();
2031 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2032 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
2033 }
2034
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09002035 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002036 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09002037 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09002038 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002039 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08002040 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08002041 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09002042 netCap.addTransportType(transportType);
2043 }
James Mattis45d81842021-01-10 14:24:24 -08002044 return createNetworkRequest(type, netCap);
2045 }
2046
2047 private NetworkRequest createNetworkRequest(
2048 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002049 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09002050 }
2051
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002052 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
2053 NetworkRequest.Type type) {
2054 final NetworkCapabilities netCap = new NetworkCapabilities();
2055 netCap.clearAll();
2056 netCap.addCapability(capability);
2057 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2058 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
2059 }
2060
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002061 // Used only for testing.
2062 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07002063 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002064 // changing ContentResolver to make registerContentObserver non-final).
2065 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
2066 // by subclassing SettingsObserver.
2067 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002068 void updateAlwaysOnNetworks() {
2069 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002070 }
2071
Erik Kline9a62f012018-03-21 07:18:33 -07002072 // See FakeSettingsProvider comment above.
2073 @VisibleForTesting
2074 void updatePrivateDnsSettings() {
2075 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
2076 }
2077
paulhu51f77dc2021-06-07 02:34:20 +00002078 @VisibleForTesting
2079 void updateMobileDataPreferredUids() {
2080 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
2081 }
2082
Patrick Rohr2857ac42022-01-21 14:58:16 +01002083 @VisibleForTesting
2084 void updateIngressRateLimit() {
2085 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
2086 }
2087
Aaron Huang40b52442021-06-08 04:34:24 +08002088 @VisibleForTesting
2089 void simulateUpdateProxyInfo(@Nullable final Network network,
2090 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08002091 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08002092 new Pair<>(network, proxyInfo)).sendToTarget();
2093 }
2094
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00002095 /**
2096 * Called when satellite network fallback uids at {@link SatelliteAccessController}
2097 * cache was updated based on {@link
2098 * android.app.role.OnRoleHoldersChangedListener#onRoleHoldersChanged(String, UserHandle)},
2099 * to create multilayer request with preference order
2100 * {@link #PREFERENCE_ORDER_SATELLITE_FALLBACK} there on.
2101 *
2102 */
2103 private void updateSatelliteNetworkPreferenceUids(Set<Integer> satelliteNetworkFallbackUids) {
2104 handleSetSatelliteNetworkPreference(satelliteNetworkFallbackUids);
2105 }
2106
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002107 private void handleAlwaysOnNetworkRequest(
2108 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002109 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002110 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002111 handleAlwaysOnNetworkRequest(networkRequest, enable);
2112 }
2113
2114 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002115 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002116 if (enable == isEnabled) {
2117 return; // Nothing to do.
2118 }
2119
2120 if (enable) {
2121 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002122 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002123 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002124 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002125 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002126 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2127 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002128 }
2129 }
2130
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002131 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002132 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2133 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2134 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2135 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002136 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2137 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002138 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002139 }
2140
paulhu51f77dc2021-06-07 02:34:20 +00002141 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002142 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002143 private void registerSettingsCallbacks() {
2144 // Watch for global HTTP proxy changes.
2145 mSettingsObserver.observe(
2146 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2147 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2148
Chalard Jean46bfbf02022-02-02 00:56:25 +09002149 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002150 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002151 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002152 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2153
Chalard Jean46bfbf02022-02-02 00:56:25 +09002154 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002155 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002156 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002157 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002158
2159 // Watch for mobile data preferred uids changes.
2160 mSettingsObserver.observe(
2161 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2162 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002163
2164 // Watch for ingress rate limit changes.
2165 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002166 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002167 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2168 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002169 }
2170
Erik Kline31b4a9e2018-01-11 21:07:29 +09002171 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002172 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2173 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002174 }
2175 }
2176
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002177 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002178 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2179 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002180 return mNextNetworkRequestId++;
2181 }
2182
junyulai74f9a8b2018-06-13 15:00:37 +08002183 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002184 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002185 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002186 if (network == null) {
2187 return null;
2188 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002189 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002190 }
2191
2192 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002193 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002194 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002195 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002196 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002197
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002198 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002199 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002200 private NetworkAgentInfo getVpnForUid(int uid) {
2201 synchronized (mNetworkForNetId) {
2202 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2203 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002204 if (nai.isVPN() && nai.everConnected()
2205 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002206 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002207 }
2208 }
2209 }
2210 return null;
2211 }
2212
Chalard Jean46bfbf02022-02-02 00:56:25 +09002213 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002214 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002215 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002216 final NetworkAgentInfo nai = getVpnForUid(uid);
2217 if (nai != null) return nai.declaredUnderlyingNetworks;
2218 return null;
2219 }
2220
Lorenzo Colittia7574052021-01-19 01:33:05 +09002221 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002222 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002223
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002224 final Network[] networks = getVpnUnderlyingNetworks(uid);
2225 if (networks != null) {
2226 // getUnderlyingNetworks() returns:
2227 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2228 // empty array => the VPN explicitly said "no default network".
2229 // non-empty array => the VPN specified one or more default networks; we use the
2230 // first one.
2231 if (networks.length > 0) {
2232 nai = getNetworkAgentInfoForNetwork(networks[0]);
2233 } else {
2234 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002235 }
2236 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002237 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002238 }
2239
2240 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002241 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002242 */
paulhu7aeba372020-12-30 00:42:19 +08002243 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2244 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002245 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002246 if (ignoreBlocked) {
2247 return false;
2248 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002249 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002250 final long ident = Binder.clearCallingIdentity();
2251 try {
2252 final boolean metered = nc == null ? true : nc.isMetered();
2253 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2254 } finally {
2255 Binder.restoreCallingIdentity(ident);
2256 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002257 }
2258
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002259 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002260 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2261 return;
2262 }
Hugo Benichi47011212017-03-30 10:46:05 +09002263 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002264 synchronized (mBlockedAppUids) {
2265 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002266 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002267 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002268 blocked = false;
2269 } else {
2270 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002271 }
2272 }
Hugo Benichi47011212017-03-30 10:46:05 +09002273 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2274 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2275 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002276 }
2277
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002278 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002279 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2280 return;
2281 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002282 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002283 final int requestId = nri.getActiveRequest() != null
2284 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002285 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002286 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002287 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002288 }
2289
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002290 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002291 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002292 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002293 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002294 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002295 @NonNull
2296 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2297 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002298 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2299 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2300 // but only exists if an app asks about them or requests them. Ensure the requesting app
2301 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002302 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002303 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2304 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2305 null /* extraInfo */);
2306 }
2307 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002308 return filtered;
2309 }
2310
2311 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2312 boolean ignoreBlocked) {
2313 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2314 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002315 }
2316
2317 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002318 * Return NetworkInfo for the active (i.e., connected) network interface.
2319 * It is assumed that at most one network is active at a time. If more
2320 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002321 * @return the info for the active network, or {@code null} if none is
2322 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002323 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002324 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002325 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002326 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002327 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002328 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002329 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2330 if (nai == null) return null;
2331 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2332 maybeLogBlockedNetworkInfo(networkInfo, uid);
2333 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002334 }
2335
Paul Jensen1f567382015-02-13 14:18:39 -05002336 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002337 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002338 public Network getActiveNetwork() {
2339 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002340 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002341 }
2342
2343 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002344 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002345 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002346 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002347 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002348 }
2349
Chalard Jean46bfbf02022-02-02 00:56:25 +09002350 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002351 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002352 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2353 if (vpnNai != null) {
2354 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2355 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2356 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002357 }
Paul Jensen1f567382015-02-13 14:18:39 -05002358 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002359
James Mattis2516da32021-01-31 17:06:19 -08002360 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002361 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2362 ignoreBlocked)) {
2363 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002364 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002365 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002366 }
2367
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002368 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002369 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002370 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002371 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002372 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2373 if (nai == null) return null;
2374 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002375 }
2376
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002377 /** Returns a NetworkInfo object for a network that doesn't exist. */
2378 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2379 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2380 getNetworkTypeName(networkType), "" /* subtypeName */);
2381 info.setIsAvailable(true);
2382 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2383 // background data is restricted.
2384 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2385 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2386 ? DetailedState.BLOCKED
2387 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002388 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2389 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002390 return info;
2391 }
2392
Lorenzo Colittia7574052021-01-19 01:33:05 +09002393 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002394 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2395 return null;
2396 }
2397 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002398 if (nai == null) {
2399 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002400 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002401 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2402 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002403 }
2404
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002405 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002406 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002407 public NetworkInfo getNetworkInfo(int networkType) {
2408 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002409 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002410 if (getVpnUnderlyingNetworks(uid) != null) {
2411 // A VPN is active, so we may need to return one of its underlying networks. This
2412 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002413 // getNetworkAgentInfoForUid.
2414 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2415 if (nai == null) return null;
2416 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2417 if (networkInfo.getType() == networkType) {
2418 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002419 }
2420 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002421 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002422 }
2423
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002424 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002425 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002426 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002427 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002428 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002429 if (nai == null) return null;
2430 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002431 }
2432
2433 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002434 public NetworkInfo[] getAllNetworkInfo() {
2435 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002436 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002437 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2438 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002439 NetworkInfo info = getNetworkInfo(networkType);
2440 if (info != null) {
2441 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002442 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002443 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002444 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002445 }
2446
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002447 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002448 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002449 public Network getNetworkForType(int networkType) {
2450 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002451 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2452 return null;
2453 }
2454 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2455 if (nai == null) {
2456 return null;
2457 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002458 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002459 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2460 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002461 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002462 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002463 }
2464
2465 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002466 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002467 public Network[] getAllNetworks() {
2468 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002469 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002470 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002471 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002472 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002473 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002474 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002475 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002476 }
2477
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002478 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002479 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002480 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002481 // The basic principle is: if an app's traffic could possibly go over a
2482 // network, without the app doing anything multinetwork-specific,
2483 // (hence, by "default"), then include that network's capabilities in
2484 // the array.
2485 //
2486 // In the normal case, app traffic only goes over the system's default
2487 // network connection, so that's the only network returned.
2488 //
2489 // With a VPN in force, some app traffic may go into the VPN, and thus
2490 // over whatever underlying networks the VPN specifies, while other app
2491 // traffic may go over the system default network (e.g.: a split-tunnel
2492 // VPN, or an app disallowed by the VPN), so the set of networks
2493 // returned includes the VPN's underlying networks and the system
2494 // default.
2495 enforceAccessPermission();
2496
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002497 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002498
James Mattis2516da32021-01-31 17:06:19 -08002499 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2500 if (!nri.isBeingSatisfied()) {
2501 continue;
2502 }
2503 final NetworkAgentInfo nai = nri.getSatisfier();
2504 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2505 if (null != nc
2506 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2507 && !result.containsKey(nai.network)) {
2508 result.put(
2509 nai.network,
2510 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002511 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002512 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2513 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002514 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002515 }
2516
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002517 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002518 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002519 if (null != networks) {
2520 for (final Network network : networks) {
2521 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2522 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002523 result.put(
2524 network,
2525 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002526 nc,
2527 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002528 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002529 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002530 }
2531 }
2532 }
2533
2534 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2535 out = result.values().toArray(out);
2536 return out;
2537 }
2538
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002539 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2540 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2541 // can call sampleConnectivityState and make the checks on it.
2542 @NonNull
2543 private StatsEvent sampleConnectivityStateToStatsEvent() {
2544 final ConnectivityStateSample sample = sampleConnectivityState();
2545 return ConnectivityStatsLog.buildStatsEvent(
2546 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2547 sample.getNetworkCountPerTransports().toByteArray(),
2548 sample.getConnectionDurationPerTransports().toByteArray(),
2549 sample.getNetworkRequestCount().toByteArray(),
2550 sample.getNetworks().toByteArray());
2551 }
2552
2553 /**
2554 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2555 *
2556 * This is used for metrics. These snapshots will be sampled and constitute a base for
2557 * statistics about connectivity state of devices.
2558 */
2559 @VisibleForTesting
2560 @NonNull
2561 public ConnectivityStateSample sampleConnectivityState() {
2562 ensureRunningOnConnectivityServiceThread();
2563 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2564 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2565 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2566 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2567 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2568 return builder.build();
2569 }
2570
2571 private static NetworkCountPerTransports sampleNetworkCount(
2572 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2573 final SparseIntArray countPerTransports = new SparseIntArray();
2574 for (final NetworkAgentInfo nai : nais) {
2575 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2576 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2577 }
2578 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2579 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2580 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2581 c.setTransportTypes(countPerTransports.keyAt(i));
2582 c.setNetworkCount(countPerTransports.valueAt(i));
2583 builder.addNetworkCountForTransports(c);
2584 }
2585 return builder.build();
2586 }
2587
2588 private static ConnectionDurationPerTransports sampleConnectionDuration(
2589 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2590 final ConnectionDurationPerTransports.Builder builder =
2591 ConnectionDurationPerTransports.newBuilder();
2592 for (final NetworkAgentInfo nai : nais) {
2593 final ConnectionDurationForTransports.Builder c =
2594 ConnectionDurationForTransports.newBuilder();
2595 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2596 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2597 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2598 // Add millisPerSecond/2 to round up or down to the nearest value
2599 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2600 builder.addConnectionDurationForTransports(c);
2601 }
2602 return builder.build();
2603 }
2604
2605 private static NetworkRequestCount sampleNetworkRequestCount(
2606 @NonNull final Collection<NetworkRequestInfo> nris) {
2607 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2608 final SparseIntArray countPerType = new SparseIntArray();
2609 for (final NetworkRequestInfo nri : nris) {
2610 final int type;
2611 if (Process.SYSTEM_UID == nri.mAsUid) {
2612 // The request is filed "as" the system, so it's the system on its own behalf.
2613 type = RequestType.RT_SYSTEM.getNumber();
2614 } else if (Process.SYSTEM_UID == nri.mUid) {
2615 // The request is filed by the system as some other app, so it's the system on
2616 // behalf of an app.
2617 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2618 } else {
2619 // Not the system, so it's an app requesting on its own behalf.
2620 type = RequestType.RT_APP.getNumber();
2621 }
2622 countPerType.put(type, countPerType.get(type, 0));
2623 }
2624 for (int i = countPerType.size() - 1; i >= 0; --i) {
2625 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2626 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2627 r.setRequestCount(countPerType.valueAt(i));
2628 builder.addRequestCountForType(r);
2629 }
2630 return builder.build();
2631 }
2632
2633 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2634 final NetworkList.Builder builder = NetworkList.newBuilder();
2635 for (final NetworkAgentInfo nai : nais) {
2636 final NetworkCapabilities nc = nai.networkCapabilities;
2637 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2638 d.setTransportTypes((int) nc.getTransportTypesInternal());
2639 final MeteredState meteredState;
2640 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2641 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2642 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2643 meteredState = MeteredState.METERED_NO;
2644 } else {
2645 meteredState = MeteredState.METERED_YES;
2646 }
2647 d.setMeteredState(meteredState);
2648 final ValidatedState validatedState;
2649 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2650 validatedState = ValidatedState.VS_PORTAL;
2651 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2652 validatedState = ValidatedState.VS_PARTIAL;
2653 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2654 validatedState = ValidatedState.VS_VALID;
2655 } else {
2656 validatedState = ValidatedState.VS_INVALID;
2657 }
2658 d.setValidatedState(validatedState);
2659 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2660 d.setCapabilities(nc.getCapabilitiesInternal());
2661 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2662 builder.addNetworkDescription(d);
2663 }
2664 return builder.build();
2665 }
2666
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002667 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002668 public boolean isNetworkSupported(int networkType) {
2669 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002670 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002671 }
2672
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002673 /**
2674 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002675 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002676 * @return the ip properties for the active network, or {@code null} if
2677 * none is active
2678 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002679 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002680 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002681 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002682 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002683 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2684 if (nai == null) return null;
2685 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002686 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002687 }
2688
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002689 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002690 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002691 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002692 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002693 final LinkProperties lp = getLinkProperties(nai);
2694 if (lp == null) return null;
2695 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002696 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002697 }
2698
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002699 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002700 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002701 public LinkProperties getLinkProperties(Network network) {
2702 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002703 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2704 if (lp == null) return null;
2705 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002706 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002707 }
2708
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002709 @Nullable
2710 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002711 if (nai == null) {
2712 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002713 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002714 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002715 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002716 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002717 }
2718
lucaslinc582d502022-01-27 09:07:00 +08002719 @Override
2720 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002721 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002722 @NonNull String packageName, @Nullable String callingAttributionTag) {
2723 Objects.requireNonNull(packageName);
2724 Objects.requireNonNull(lp);
2725 enforceNetworkStackOrSettingsPermission();
Junyu Lai71b51532024-02-01 10:39:01 +08002726 if (!hasAccessPermission(-1 /* pid */, uid)) {
lucaslinc582d502022-01-27 09:07:00 +08002727 return null;
2728 }
2729 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2730 }
2731
Qingxi Lib2748102020-01-08 12:51:49 -08002732 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2733 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2734 }
2735
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002736 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002737 if (nai == null) return null;
2738 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002739 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002740 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002741 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002742 }
2743
2744 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002745 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2746 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002747 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002748 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002749 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002750 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002751 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002752 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002753 }
2754
lucaslinc582d502022-01-27 09:07:00 +08002755 @Override
lucaslind2b06132022-03-02 10:56:57 +08002756 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2757 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2758 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002759 Objects.requireNonNull(nc);
2760 Objects.requireNonNull(packageName);
2761 enforceNetworkStackOrSettingsPermission();
Junyu Lai71b51532024-02-01 10:39:01 +08002762 if (!hasAccessPermission(-1 /* pid */, uid)) {
lucaslinc582d502022-01-27 09:07:00 +08002763 return null;
2764 }
2765 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2766 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2767 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2768 callingAttributionTag);
2769 }
2770
lucaslin69e1aa92022-03-22 18:15:09 +08002771 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2772 if (nc.getUnderlyingNetworks() != null
Junyu Lai71b51532024-02-01 10:39:01 +08002773 && !hasNetworkFactoryOrSettingsPermission(pid, uid)) {
lucaslin69e1aa92022-03-22 18:15:09 +08002774 nc.setUnderlyingNetworks(null);
2775 }
2776 }
2777
Chalard Jean53017782022-11-24 17:13:44 +09002778 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
2779 return Process.SYSTEM_UID == uid
Junyu Lai71b51532024-02-01 10:39:01 +08002780 || hasAnyPermissionOf(mContext, pid, uid,
Chalard Jean53017782022-11-24 17:13:44 +09002781 android.Manifest.permission.NETWORK_FACTORY);
2782 }
2783
Qingxi Libb8da982020-01-17 17:54:27 -08002784 @VisibleForTesting
2785 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002786 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002787 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2788 // this would be expensive (one more permission check every time any NC callback is
2789 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2790 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2791 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002792 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Junyu Lai71b51532024-02-01 10:39:01 +08002793 if (!hasSettingsPermission(callerPid, callerUid)) {
Chalard Jean46adcf32018-04-18 20:18:38 +09002794 newNc.setUids(null);
2795 newNc.setSSID(null);
2796 }
Etan Cohen107ae952018-12-30 17:59:59 -08002797 if (newNc.getNetworkSpecifier() != null) {
2798 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2799 }
Junyu Lai71b51532024-02-01 10:39:01 +08002800 if (!hasAnyPermissionOf(mContext, callerPid, callerUid,
Junyu Lai4c6fe232023-04-11 11:33:46 +08002801 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002802 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2803 newNc.setAdministratorUids(new int[0]);
2804 }
Chalard Jean53017782022-11-24 17:13:44 +09002805 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09002806 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002807 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002808 }
lucaslin69e1aa92022-03-22 18:15:09 +08002809 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002810
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002811 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002812 }
2813
Roshan Pius98f59ec2021-02-23 08:47:39 -08002814 /**
2815 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002816 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002817 * NetworkCapabilities.
2818 * Note: This wrapper does not support any sort of invalidation and thus must not be
2819 * persistent or long-lived. It may only be used for the time necessary to
2820 * compute the redactions required by one particular NetworkCallback or
2821 * synchronous call.
2822 */
2823 private class RedactionPermissionChecker {
2824 private final int mCallingPid;
2825 private final int mCallingUid;
2826 @NonNull private final String mCallingPackageName;
2827 @Nullable private final String mCallingAttributionTag;
2828
2829 private Boolean mHasLocationPermission = null;
2830 private Boolean mHasLocalMacAddressPermission = null;
2831 private Boolean mHasSettingsPermission = null;
2832
2833 RedactionPermissionChecker(int callingPid, int callingUid,
2834 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2835 mCallingPid = callingPid;
2836 mCallingUid = callingUid;
2837 mCallingPackageName = callingPackageName;
2838 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002839 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002840
2841 private boolean hasLocationPermissionInternal() {
2842 final long token = Binder.clearCallingIdentity();
2843 try {
2844 return mLocationPermissionChecker.checkLocationPermission(
2845 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2846 null /* message */);
2847 } finally {
2848 Binder.restoreCallingIdentity(token);
2849 }
2850 }
2851
2852 /**
2853 * Returns whether the app holds location permission or not (might return cached result
2854 * if the permission was already checked before).
2855 */
2856 public boolean hasLocationPermission() {
2857 if (mHasLocationPermission == null) {
2858 // If there is no cached result, perform the check now.
2859 mHasLocationPermission = hasLocationPermissionInternal();
2860 }
2861 return mHasLocationPermission;
2862 }
2863
2864 /**
2865 * Returns whether the app holds local mac address permission or not (might return cached
2866 * result if the permission was already checked before).
2867 */
Junyu Lai71b51532024-02-01 10:39:01 +08002868 @CheckResult
Roshan Pius98f59ec2021-02-23 08:47:39 -08002869 public boolean hasLocalMacAddressPermission() {
2870 if (mHasLocalMacAddressPermission == null) {
2871 // If there is no cached result, perform the check now.
Junyu Lai71b51532024-02-01 10:39:01 +08002872 mHasLocalMacAddressPermission = ConnectivityService.this
2873 .hasLocalMacAddressPermission(mCallingPid, mCallingUid);
Roshan Pius98f59ec2021-02-23 08:47:39 -08002874 }
2875 return mHasLocalMacAddressPermission;
2876 }
2877
2878 /**
2879 * Returns whether the app holds settings permission or not (might return cached
2880 * result if the permission was already checked before).
2881 */
Junyu Lai71b51532024-02-01 10:39:01 +08002882 @CheckResult
Roshan Pius98f59ec2021-02-23 08:47:39 -08002883 public boolean hasSettingsPermission() {
2884 if (mHasSettingsPermission == null) {
2885 // If there is no cached result, perform the check now.
Junyu Lai71b51532024-02-01 10:39:01 +08002886 mHasSettingsPermission =
2887 ConnectivityService.this.hasSettingsPermission(mCallingPid, mCallingUid);
Roshan Pius98f59ec2021-02-23 08:47:39 -08002888 }
2889 return mHasSettingsPermission;
2890 }
2891 }
2892
2893 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2894 @NetworkCapabilities.NetCapability long redaction) {
2895 return (redactions & redaction) != 0;
2896 }
2897
2898 /**
2899 * Use the provided |applicableRedactions| to check the receiving app's
2900 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2901 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2902 * before being sent to the corresponding app.
2903 */
2904 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2905 @NetworkCapabilities.RedactionType long applicableRedactions,
2906 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2907 boolean includeLocationSensitiveInfo) {
2908 long redactions = applicableRedactions;
2909 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2910 if (includeLocationSensitiveInfo
2911 && redactionPermissionChecker.hasLocationPermission()) {
2912 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2913 }
2914 }
2915 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2916 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2917 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2918 }
2919 }
2920 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2921 if (redactionPermissionChecker.hasSettingsPermission()) {
2922 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2923 }
2924 }
2925 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002926 }
2927
Qingxi Lib2748102020-01-08 12:51:49 -08002928 @VisibleForTesting
2929 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002930 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002931 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002932 int callingPid, int callingUid, @NonNull String callingPkgName,
2933 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002934 if (nc == null) {
2935 return null;
2936 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002937 // Avoid doing location permission check if the transport info has no location sensitive
2938 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002939 final RedactionPermissionChecker redactionPermissionChecker =
2940 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2941 callingAttributionTag);
2942 final long redactions = retrieveRequiredRedactions(
2943 nc.getApplicableRedactions(), redactionPermissionChecker,
2944 includeLocationSensitiveInfo);
2945 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002946 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002947 // TODO : calling UID is redacted because apps should generally not know what UID is
2948 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002949 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002950 newNc.setOwnerUid(INVALID_UID);
2951 return newNc;
2952 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002953 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2954 if (nc.hasTransport(TRANSPORT_VPN)) {
2955 // Owner UIDs already checked above. No need to re-check.
2956 return newNc;
2957 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002958 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2959 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002960 // compatibility for older apps.
2961 if (!includeLocationSensitiveInfo
2962 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002963 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002964 newNc.setOwnerUid(INVALID_UID);
2965 return newNc;
2966 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002967 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002968 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002969 newNc.setOwnerUid(INVALID_UID);
2970 }
Qingxi Lib2748102020-01-08 12:51:49 -08002971 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002972 }
2973
lucaslinc582d502022-01-27 09:07:00 +08002974 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002975 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2976 LinkProperties lp, int callerPid, int callerUid) {
2977 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002978 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2979 // this would be expensive (one more permission check every time any LP callback is
2980 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2981 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2982 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002983
2984 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2985 final boolean needsSanitization =
2986 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2987 if (!needsSanitization) {
2988 return new LinkProperties(lp);
2989 }
2990
Junyu Lai71b51532024-02-01 10:39:01 +08002991 if (hasSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002992 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002993 }
2994
2995 final LinkProperties newLp = new LinkProperties(lp);
2996 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2997 // object gets parceled.
2998 newLp.setCaptivePortalApiUrl(null);
2999 newLp.setCaptivePortalData(null);
3000 return newLp;
3001 }
3002
Roshan Pius08c94fb2020-01-16 12:17:17 -08003003 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
3004 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003005 // There is no need to track the effective UID of the request here. If the caller
3006 // lacks the settings permission, the effective UID is the same as the calling ID.
Junyu Lai71b51532024-02-01 10:39:01 +08003007 if (!hasSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003008 // Unprivileged apps can only pass in null or their own UID.
3009 if (nc.getUids() == null) {
3010 // If the caller passes in null, the callback will also match networks that do not
3011 // apply to its UID, similarly to what it would see if it called getAllNetworks.
3012 // In this case, redact everything in the request immediately. This ensures that the
3013 // app is not able to get any redacted information by filing an unredacted request
3014 // and observing whether the request matches something.
3015 if (nc.getNetworkSpecifier() != null) {
3016 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
3017 }
3018 } else {
3019 nc.setSingleUid(callerUid);
3020 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09003021 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08003022 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07003023 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08003024
3025 // Clear owner UID; this can never come from an app.
3026 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003027 }
3028
Chalard Jean38354d12018-03-20 19:13:57 +09003029 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003030 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09003031 nc.addCapability(NET_CAPABILITY_FOREGROUND);
3032 }
3033 }
3034
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09003035 @Override
3036 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
3037 enforceAccessPermission();
3038 final int callerUid = Binder.getCallingUid();
3039 final long token = Binder.clearCallingIdentity();
3040 try {
3041 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
3042 } finally {
3043 Binder.restoreCallingIdentity(token);
3044 }
3045 }
3046
junyulaiebd15162021-03-03 12:09:05 +08003047 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003048 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07003049 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08003050 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08003051 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08003052
Serik Beketayev05130302021-01-15 16:47:25 -08003053 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08003054 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08003055 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
3056 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08003057 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08003058 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08003059 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08003060 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
3061 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07003062 }
3063 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09003064 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07003065 }
3066
Jeff Sharkey66fa9682011-08-02 17:22:34 -07003067 @Override
junyulaiebd15162021-03-03 12:09:05 +08003068 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08003069 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08003070 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08003071 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08003072
3073 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
3074 for (Network network : getAllNetworks()) {
3075 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09003076 final boolean includeNetwork = (nai != null) && nai.isCreated();
3077 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08003078 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
3079 // NetworkCapabilities, which may contain UIDs of apps to which the
3080 // network applies. Should the UIDs be cleared so as not to leak or
3081 // interfere ?
3082 result.add(nai.getNetworkStateSnapshot());
3083 }
3084 }
3085 return result;
3086 }
3087
3088 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003089 public boolean isActiveNetworkMetered() {
3090 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003091
Qingxi Lib2748102020-01-08 12:51:49 -08003092 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06003093 if (caps != null) {
3094 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3095 } else {
3096 // Always return the most conservative value
3097 return true;
3098 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07003099 }
3100
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003101 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09003102 * Ensures that the system cannot call a particular method.
3103 */
3104 private boolean disallowedBecauseSystemCaller() {
3105 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07003106 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
3107 // for devices launched with Q and above. However, existing devices upgrading to Q and
3108 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003109 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07003110 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003111 log("This method exists only for app backwards compatibility"
3112 + " and must not be called by system services.");
3113 return true;
3114 }
3115 return false;
3116 }
3117
3118 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003119 * Ensure that a network route exists to deliver traffic to the specified
3120 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003121 * @param networkType the type of the network over which traffic to the
3122 * specified host is to be routed
3123 * @param hostAddress the IP address of the host to which the route is
3124 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003125 * @return {@code true} on success, {@code false} on failure
3126 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003127 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003128 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3129 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003130 if (disallowedBecauseSystemCaller()) {
3131 return false;
3132 }
Junyu Lai8fdc4312024-01-16 11:19:43 +08003133 PermissionUtils.enforcePackageNameMatchesUid(
3134 mContext, mDeps.getCallingUid(), callingPackageName);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003135 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003136 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003137 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003138 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003139
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003140 InetAddress addr;
3141 try {
3142 addr = InetAddress.getByAddress(hostAddress);
3143 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003144 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003145 return false;
3146 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003147
The Android Open Source Project28527d22009-03-03 19:31:44 -08003148 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003149 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003150 return false;
3151 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003152
3153 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3154 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003155 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003156 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3157 } else {
3158 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3159 }
3160 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003161 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003162
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003163 DetailedState netState;
3164 synchronized (nai) {
3165 netState = nai.networkInfo.getDetailedState();
3166 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003167
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003168 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003169 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003170 log("requestRouteToHostAddress on down network "
3171 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003172 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003173 }
3174 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003175 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003176
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003177 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003178 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003179 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003180 LinkProperties lp;
3181 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003182 synchronized (nai) {
3183 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003184 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003185 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003186 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003187 if (DBG) {
3188 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3189 }
Wink Saville32506bc2013-06-29 21:10:57 -07003190 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003191 } finally {
3192 Binder.restoreCallingIdentity(token);
3193 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003194 }
3195
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003196 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003197 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003198 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003199 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003200 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003201 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003202 if (bestRoute.getGateway().equals(addr)) {
3203 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003204 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003205 } else {
3206 // if we will connect to this through another route, add a direct route
3207 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003208 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003209 }
3210 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003211 if (DBG) log("Adding legacy route " + bestRoute +
3212 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003213
3214 final String dst = bestRoute.getDestinationLinkAddress().toString();
3215 final String nextHop = bestRoute.hasGateway()
3216 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003217 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003218 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3219 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003220 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003221 return false;
3222 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003223 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003224 }
3225
paulhu7c0a2e62021-01-08 00:51:49 +08003226 class DnsResolverUnsolicitedEventCallback extends
3227 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003228 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003229 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003230 try {
3231 mHandler.sendMessage(mHandler.obtainMessage(
3232 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003233 new PrivateDnsValidationUpdate(event.netId,
3234 InetAddresses.parseNumericAddress(event.ipAddress),
3235 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003236 } catch (IllegalArgumentException e) {
3237 loge("Error parsing ip address in validation event");
3238 }
3239 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003240
3241 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003242 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3243 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003244 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3245 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3246 // event callback for certain nai. e.g. cellular. Register here to pass to
3247 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003248 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003249 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3250 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003251 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003252 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003253 }
3254 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003255
3256 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003257 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3258 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3259 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003260 }
dalyk1720e542018-03-05 12:42:22 -05003261
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003262 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003263 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003264 return this.VERSION;
3265 }
3266
3267 @Override
3268 public String getInterfaceHash() {
3269 return this.HASH;
3270 }
paulhu7c0a2e62021-01-08 00:51:49 +08003271 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003272
3273 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003274 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3275 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003276
paulhu7c0a2e62021-01-08 00:51:49 +08003277 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003278 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003279 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003280 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003281 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003282 }
3283 }
3284
Sudheer Shanka9967d462021-03-18 19:09:25 +00003285 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003286 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003287 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003288 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3289 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003290 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003291 };
3292
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003293 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003294 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003295 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003296 }
3297
Mark Fasheh7c999d82023-05-04 20:23:11 +00003298 static final class UidFrozenStateChangedArgs {
3299 final int[] mUids;
3300 final int[] mFrozenStates;
3301
3302 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3303 mUids = uids;
3304 mFrozenStates = frozenStates;
3305 }
3306 }
3307
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003308 /**
3309 * Check if the cell network is idle.
3310 * @return true if the cell network state is idle
3311 * false if the cell network state is active or unknown
3312 */
3313 private boolean isCellNetworkIdle() {
3314 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3315 if (defaultNai == null
3316 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3317 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3318 // cell network is not the default network, cell network state is unknown.
3319 // TODO(b/279380356): Track cell network state when the cell is not the default network
3320 return false;
3321 }
3322
3323 return !mNetworkActivityTracker.isDefaultNetworkActive();
3324 }
3325
Mark Fasheh7c999d82023-05-04 20:23:11 +00003326 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003327 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003328
3329 for (int i = 0; i < uids.length; i++) {
3330 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003331 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003332 } else {
3333 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003334 }
3335 }
3336
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003337 if (ownerUids.isEmpty()) {
3338 return;
3339 }
3340
3341 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3342 // Delay closing sockets to avoid waking the cell modem up.
3343 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3344 // than waking cell modem up.
3345 mPendingFrozenUids.addAll(ownerUids);
3346 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003347 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003348 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003349 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003350 loge("Exception in socket destroy: " + e);
3351 }
3352 }
3353 }
3354
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003355 private void closePendingFrozenSockets() {
3356 ensureRunningOnConnectivityServiceThread();
3357
3358 try {
3359 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3360 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3361 loge("Failed to close pending frozen app sockets: " + e);
3362 }
3363 mPendingFrozenUids.clear();
3364 }
3365
3366 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3367 mNetworkActivityTracker.handleReportNetworkActivity(params);
3368
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003369 final boolean isCellNetworkActivity;
3370 if (mTrackMultiNetworkActivities) {
3371 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3372 // nai could be null if netd receives a netlink message and calls the network
3373 // activity change callback after the network is unregistered from ConnectivityService.
3374 isCellNetworkActivity = nai != null
3375 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3376 } else {
3377 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3378 }
3379
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003380 if (mDelayDestroyFrozenSockets
3381 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003382 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003383 && !mPendingFrozenUids.isEmpty()) {
3384 closePendingFrozenSockets();
3385 }
3386 }
3387
3388 /**
3389 * If the cellular network is no longer the default network, close pending frozen sockets.
3390 *
3391 * @param newNetwork new default network
3392 * @param oldNetwork old default network
3393 */
3394 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3395 NetworkAgentInfo oldNetwork) {
3396 final boolean isOldNetworkCellular = oldNetwork != null
3397 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3398 final boolean isNewNetworkCellular = newNetwork != null
3399 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3400
3401 if (isOldNetworkCellular
3402 && !isNewNetworkCellular
3403 && !mPendingFrozenUids.isEmpty()) {
3404 closePendingFrozenSockets();
3405 }
3406 }
3407
3408 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3409 pw.println("CloseFrozenAppSockets:");
3410 pw.increaseIndent();
3411 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3412 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3413 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3414 pw.decreaseIndent();
3415 }
3416
Junyu Lai155760b2023-10-05 14:51:00 +08003417 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3418 pw.println("Bpf Program Status:");
3419 pw.increaseIndent();
3420 try {
3421 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003422 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003423 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003424 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003425 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003426 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003427 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003428 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003429 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003430 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003431 } catch (IOException e) {
3432 pw.println(" IOException");
3433 }
3434 pw.decreaseIndent();
3435 }
3436
Mark Fasheh7c999d82023-05-04 20:23:11 +00003437 @VisibleForTesting
3438 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003439 @VisibleForTesting
3440 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3441 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003442
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003443 @VisibleForTesting
3444 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3445 "allow_sysui_connectivity_reports";
3446
Yuyang Huang41557552023-11-28 12:47:22 +09003447 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
3448
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00003449 public static final String ALLOW_SATALLITE_NETWORK_FALLBACK =
3450 "allow_satallite_network_fallback";
3451
Paul Jensen83f5d572014-08-29 09:54:01 -04003452 private void enforceInternetPermission() {
3453 mContext.enforceCallingOrSelfPermission(
3454 android.Manifest.permission.INTERNET,
3455 "ConnectivityService");
3456 }
3457
The Android Open Source Project28527d22009-03-03 19:31:44 -08003458 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003459 mContext.enforceCallingOrSelfPermission(
3460 android.Manifest.permission.ACCESS_NETWORK_STATE,
3461 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003462 }
3463
Junyu Lai71b51532024-02-01 10:39:01 +08003464 @CheckResult
3465 private boolean hasAccessPermission(int pid, int uid) {
lucaslinc582d502022-01-27 09:07:00 +08003466 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3467 == PERMISSION_GRANTED;
3468 }
3469
paulhua6ee2122021-02-22 15:40:43 +08003470 /**
3471 * Performs a strict and comprehensive check of whether a calling package is allowed to
3472 * change the state of network, as the condition differs for pre-M, M+, and
3473 * privileged/preinstalled apps. The caller is expected to have either the
3474 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3475 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3476 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3477 * permission and cannot be revoked. See http://b/23597341
3478 *
3479 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3480 * of this app will be updated to the current time.
3481 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003482 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003483 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3484 == PackageManager.PERMISSION_GRANTED) {
3485 return;
3486 }
3487
3488 if (callingPkg == null) {
3489 throw new SecurityException("Calling package name is null.");
3490 }
3491
3492 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3493 final int uid = mDeps.getCallingUid();
3494 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3495 callingPkg, callingAttributionTag, null /* message */);
3496
3497 if (mode == AppOpsManager.MODE_ALLOWED) {
3498 return;
3499 }
3500
3501 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3502 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3503 return;
3504 }
3505
3506 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3507 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3508 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003509 }
3510
Charles He9369e612017-05-15 17:07:18 +01003511 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003512 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003513 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003514 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003515 }
3516
Quang Luong98858d62023-02-11 00:25:24 +00003517 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003518 enforceAnyPermissionOf(mContext,
3519 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003520 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003521 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3522 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3523 }
3524
paulhu8e96a752019-08-12 16:25:11 +08003525 private void enforceNetworkFactoryPermission() {
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,
paulhu8e96a752019-08-12 16:25:11 +08003529 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003530 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003531 }
3532
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003533 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003534 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003535 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003536 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003537 android.Manifest.permission.NETWORK_SETTINGS,
3538 android.Manifest.permission.NETWORK_FACTORY,
3539 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3540 }
3541
3542 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003543 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003544 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003545 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003546 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3547 android.Manifest.permission.NETWORK_FACTORY,
3548 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3549 }
3550
Junyu Lai71b51532024-02-01 10:39:01 +08003551 @CheckResult
3552 private boolean hasNetworkFactoryOrSettingsPermission(int pid, int uid) {
lucaslin69e1aa92022-03-22 18:15:09 +08003553 return PERMISSION_GRANTED == mContext.checkPermission(
3554 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3555 || PERMISSION_GRANTED == mContext.checkPermission(
3556 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3557 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003558 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003559 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003560 }
3561
Junyu Lai71b51532024-02-01 10:39:01 +08003562 @CheckResult
3563 private boolean hasSettingsPermission() {
3564 return hasAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003565 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003566 }
3567
Junyu Lai71b51532024-02-01 10:39:01 +08003568 @CheckResult
3569 private boolean hasSettingsPermission(int pid, int uid) {
Chalard Jean9a396cc2018-02-21 18:43:54 +09003570 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003571 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3572 || PERMISSION_GRANTED == mContext.checkPermission(
3573 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003574 }
3575
paulhu8e96a752019-08-12 16:25:11 +08003576 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003577 enforceNetworkStackPermissionOr(mContext,
3578 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003579 }
3580
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003581 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003582 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003583 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003584 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003585 }
3586
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003587 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003588 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003589 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3590 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003591 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003592 }
3593
James Mattis8378aec2021-01-26 14:05:36 -08003594 private void enforceOemNetworkPreferencesPermission() {
3595 mContext.enforceCallingOrSelfPermission(
3596 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3597 "ConnectivityService");
3598 }
3599
James Mattisfa270db2021-05-31 17:11:10 -07003600 private void enforceManageTestNetworksPermission() {
3601 mContext.enforceCallingOrSelfPermission(
3602 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3603 "ConnectivityService");
3604 }
3605
Junyu Lai71b51532024-02-01 10:39:01 +08003606 @CheckResult
3607 private boolean hasNetworkStackPermission() {
3608 return hasAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003609 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003610 }
3611
Junyu Lai71b51532024-02-01 10:39:01 +08003612 @CheckResult
3613 private boolean hasNetworkStackPermission(int pid, int uid) {
3614 return hasAnyPermissionOf(mContext, pid, uid, android.Manifest.permission.NETWORK_STACK,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003615 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3616 }
3617
Junyu Lai71b51532024-02-01 10:39:01 +08003618 @CheckResult
3619 private boolean hasSystemBarServicePermission(int pid, int uid) {
3620 return hasAnyPermissionOf(mContext, pid, uid,
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003621 android.Manifest.permission.STATUS_BAR_SERVICE);
3622 }
3623
Junyu Lai71b51532024-02-01 10:39:01 +08003624 @CheckResult
3625 private boolean hasNetworkSignalStrengthWakeupPermission(int pid, int uid) {
3626 return hasAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003627 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003628 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3629 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003630 }
3631
Junyu Lai71b51532024-02-01 10:39:01 +08003632 @CheckResult
3633 private boolean hasConnectivityRestrictedNetworksPermission(int callingUid,
Paul Hu8fc2a552022-05-04 18:44:42 +08003634 boolean checkUidsAllowedList) {
Junyu Lai71b51532024-02-01 10:39:01 +08003635 if (hasAnyPermissionOf(mContext,
Paul Hu8fc2a552022-05-04 18:44:42 +08003636 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3637 return true;
3638 }
3639
3640 // fallback to ConnectivityInternalPermission
3641 // TODO: Remove this fallback check after all apps have declared
3642 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
Junyu Lai71b51532024-02-01 10:39:01 +08003643 if (hasAnyPermissionOf(mContext, android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003644 return true;
3645 }
3646
3647 // Check whether uid is in allowed on restricted networks list.
3648 if (checkUidsAllowedList
3649 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3650 return true;
3651 }
3652 return false;
3653 }
3654
3655 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3656 final int callingUid = mDeps.getCallingUid();
Junyu Lai71b51532024-02-01 10:39:01 +08003657 if (!hasConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003658 throw new SecurityException("ConnectivityService: user " + callingUid
3659 + " has no permission to access restricted network.");
3660 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003661 }
3662
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003663 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003664 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003665 }
3666
Junyu Lai71b51532024-02-01 10:39:01 +08003667 @CheckResult
3668 private boolean hasLocalMacAddressPermission(int pid, int uid) {
Roshan Pius98f59ec2021-02-23 08:47:39 -08003669 return PERMISSION_GRANTED == mContext.checkPermission(
3670 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3671 }
3672
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003673 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003674 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003675 }
3676
3677 private void sendInetConditionBroadcast(NetworkInfo info) {
3678 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3679 }
3680
Wink Saville4f0de1e2011-08-04 15:01:58 -07003681 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003682 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003683 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003684 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003685 if (info.isFailover()) {
3686 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3687 info.setFailover(false);
3688 }
3689 if (info.getReason() != null) {
3690 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3691 }
3692 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003693 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3694 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003695 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003696 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003697 return intent;
3698 }
3699
3700 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3701 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3702 }
3703
Michael Groover73f69482023-01-27 11:01:25 -06003704 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3705 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003706 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3707 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003708 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003709 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003710 if (!mSystemReady
3711 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003712 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003713 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003714 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003715 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003716 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003717 }
3718
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003719 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003720 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003721 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003722 final NetworkInfo ni = intent.getParcelableExtra(
3723 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003724 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3725 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003726 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003727 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003728 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003729 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003730 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003731 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003732 } finally {
3733 Binder.restoreCallingIdentity(ident);
3734 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003735 }
3736 }
3737
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003738 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3739 NetworkInfo info) {
3740 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003741 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003742
3743 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3744 try {
3745 // This allows us to discard older broadcasts still waiting to be delivered
3746 // which have the same namespace and key.
3747 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3748 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3749 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003750 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003751 } catch (UnsupportedApiLevelException e) {
3752 Log.wtf(TAG, "Using unsupported API" + e);
3753 }
3754 }
3755
3756 @VisibleForTesting
3757 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3758 final StringBuilder sb = new StringBuilder();
3759 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3760 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3761 sb.append(info.getExtraInfo());
3762 return sb.toString();
3763 }
3764
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003765 /**
Aaron Huang96011892020-06-27 07:18:23 +08003766 * Called by SystemServer through ConnectivityManager when the system is ready.
3767 */
3768 @Override
3769 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003770 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003771 throw new SecurityException("Calling Uid is not system uid.");
3772 }
3773 systemReadyInternal();
3774 }
3775
3776 /**
3777 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003778 */
3779 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003780 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003781 // Load flags after PackageManager is ready to query module version
3782 mFlags.loadFlags(mDeps, mContext);
3783
Aaron Huang9a57acf2020-12-08 10:03:29 +08003784 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3785 // listening network request which is sent by MultipathPolicyTracker won't be added
3786 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3787 // be called after PermissionMonitor#startMonitoring().
3788 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3789 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3790 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003791 final ConditionVariable startMonitoringDone = new ConditionVariable();
3792 mHandler.post(() -> {
3793 mPermissionMonitor.startMonitoring();
3794 startMonitoringDone.open();
3795 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003796 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003797 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003798
Hugo Benichie5220992017-04-26 14:53:28 +09003799 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003800 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003801 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003802 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003803 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003804 }
3805 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003806
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003807 // Create network requests for always-on networks.
3808 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003809
3810 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003811 // Note that updating can be skipped here if the list is empty only because no uid
3812 // rules are applied before system ready. Normally, the empty uid list means to clear
3813 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003814 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3815 updateMobileDataPreferredUids();
3816 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003817
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00003818 if (mSatelliteAccessController != null) {
3819 mSatelliteAccessController.start();
3820 }
3821
Motomu Utsumi166f9662022-09-01 10:35:29 +09003822 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003823 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003824 mBpfNetMaps.setPullAtomCallback(mContext);
3825 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003826 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3827 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003828 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3829 // have permission problem. While CV#block() is unbounded in time and can in principle block
3830 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3831 // could have blocked forever too.
3832 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003833 }
3834
The Android Open Source Project28527d22009-03-03 19:31:44 -08003835 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003836 * Start listening for default data network activity state changes.
3837 */
3838 @Override
3839 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003840 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003841 }
3842
3843 /**
3844 * Stop listening for default data network activity state changes.
3845 */
3846 @Override
3847 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003848 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003849 }
3850
3851 /**
3852 * Check whether the default network radio is currently active.
3853 */
3854 @Override
3855 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003856 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003857 }
3858
3859 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003860 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003861 * and set it on it's iface.
3862 */
Junyu Lai970963e2022-10-25 15:46:47 +08003863 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003864 final String iface = newLp.getInterfaceName();
3865 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003866 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003867 // Silently ignore unset MTU value.
3868 return;
3869 }
Hansen Kurli04252032022-12-07 11:21:49 +00003870 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3871 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3872 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003873 return;
3874 }
Hansen Kurli04252032022-12-07 11:21:49 +00003875 // Cannot set MTU without interface name
3876 if (TextUtils.isEmpty(iface)) {
3877 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003878 return;
3879 }
sy.yun4aa73922013-09-02 05:24:09 +09003880
Hansen Kurli04252032022-12-07 11:21:49 +00003881 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3882 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003883 return;
3884 }
3885
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003886 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003887 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003888 mNetd.interfaceSetMtu(iface, mtu);
3889 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003890 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003891 }
3892 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003893
Chenbo Feng15416292018-11-08 17:36:21 -08003894 @VisibleForTesting
3895 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003896
Junyu Lai970963e2022-10-25 15:46:47 +08003897 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003898 String[] values = null;
3899 if (tcpBufferSizes != null) {
3900 values = tcpBufferSizes.split(",");
3901 }
3902
3903 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003904 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003905 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3906 values = tcpBufferSizes.split(",");
3907 }
3908
3909 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3910
3911 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003912 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003913
Chenbo Feng15416292018-11-08 17:36:21 -08003914 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3915 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3916 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003917 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003918 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003919 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003920 }
3921 }
3922
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003923 @Override
3924 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003925 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003926 NETWORK_RESTORE_DELAY_PROP_NAME);
3927 if(restoreDefaultNetworkDelayStr != null &&
3928 restoreDefaultNetworkDelayStr.length() != 0) {
3929 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003930 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003931 } catch (NumberFormatException e) {
3932 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003933 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003934 // if the system property isn't set, use the value for the apn type
3935 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3936
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003937 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3938 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003939 }
3940 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003941 }
3942
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003943 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003944 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003945 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003946 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003947 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003948 // Start gathering diagnostic information.
3949 netDiags.add(new NetworkDiagnostics(
3950 nai.network,
3951 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003952 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003953 DIAG_TIME_MS));
3954 }
3955
3956 for (NetworkDiagnostics netDiag : netDiags) {
3957 pw.println();
3958 netDiag.waitForMeasurements();
3959 netDiag.dump(pw);
3960 }
3961 }
3962
The Android Open Source Project28527d22009-03-03 19:31:44 -08003963 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003964 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3965 @Nullable String[] args) {
Junyu Lai71b51532024-02-01 10:39:01 +08003966 if (!hasDumpPermission(mContext, TAG, writer)) return;
Chiachang Wanga101f852021-04-19 10:59:24 +08003967
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003968 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003969 }
3970
Junyu Lai71b51532024-02-01 10:39:01 +08003971 @CheckResult
3972 private boolean hasDumpPermission(Context context, String tag, PrintWriter pw) {
lucaslin99473f62020-12-10 15:10:54 +08003973 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3974 != PackageManager.PERMISSION_GRANTED) {
3975 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003976 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003977 + " due to missing android.permission.DUMP permission");
3978 return false;
3979 } else {
3980 return true;
3981 }
3982 }
3983
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003984 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003985 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003986
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003987 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003988 dumpNetworkDiagnostics(pw);
3989 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003990 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003991 dumpNetworks(pw);
3992 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003993 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003994 dumpNetworkRequests(pw);
3995 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003996 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3997 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3998 dumpTrafficController(pw, fd, verbose);
3999 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004000 }
Erik Kline9647f382015-06-05 17:47:34 +09004001
Junyu Lai0da479b2022-04-20 15:06:29 +08004002 pw.println("NetworkProviders for:");
4003 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004004 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08004005 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004006 }
Junyu Lai0da479b2022-04-20 15:06:29 +08004007 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004008 pw.println();
4009
Chalard Jean5b409c72021-02-04 13:12:59 +09004010 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004011 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09004012 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004013 pw.println("none");
4014 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09004015 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08004016 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08004017 pw.println();
4018
James Mattis8b298a02021-06-01 22:34:04 -07004019 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08004020 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07004021 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08004022 pw.decreaseIndent();
4023 pw.println();
4024
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004025 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004026 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004027 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004028 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004029 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08004030
junyulaif2c67e42018-08-07 19:50:45 +08004031 pw.println("Status for known UIDs:");
4032 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00004033 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08004034 for (int i = 0; i < size; i++) {
4035 // Don't crash if the array is modified while dumping in bugreports.
4036 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00004037 final int uid = mUidBlockedReasons.keyAt(i);
4038 final int blockedReasons = mUidBlockedReasons.valueAt(i);
4039 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00004040 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08004041 } catch (ArrayIndexOutOfBoundsException e) {
4042 pw.println(" ArrayIndexOutOfBoundsException");
4043 } catch (ConcurrentModificationException e) {
4044 pw.println(" ConcurrentModificationException");
4045 }
4046 }
4047 pw.println();
4048 pw.decreaseIndent();
4049
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004050 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004051 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004052 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004053 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004054 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004055
Junyu Lai0da479b2022-04-20 15:06:29 +08004056 pw.println("Network Offers:");
4057 pw.increaseIndent();
4058 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
4059 pw.println(offerInfo.offer);
4060 }
4061 pw.decreaseIndent();
4062 pw.println();
4063
Robert Greenwalt94e22142014-07-30 16:31:24 -07004064 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07004065
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004066 pw.println();
markchien5e866652019-09-30 14:40:57 +08004067 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07004068
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004069 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004070 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004071
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004072 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004073 dumpCloseFrozenAppSockets(pw);
4074
4075 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08004076 dumpBpfProgramStatus(pw);
4077
Chalard Jean53017782022-11-24 17:13:44 +09004078 if (null != mCarrierPrivilegeAuthenticator) {
4079 pw.println();
4080 mCarrierPrivilegeAuthenticator.dump(pw);
4081 }
4082
Junyu Lai155760b2023-10-05 14:51:00 +08004083 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004084
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004085 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004086 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09004087 pw.println("mNetworkRequestInfoLogs (most recent first):");
4088 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004089 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09004090 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09004091
4092 pw.println();
4093 pw.println("mNetworkInfoBlockingLogs (most recent first):");
4094 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004095 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09004096 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09004097
4098 pw.println();
4099 pw.println("NetTransition WakeLock activity (most recent first):");
4100 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004101 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
4102 pw.println("total releases: " + mTotalWakelockReleases);
4103 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
4104 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
4105 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4106 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4107 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4108 }
James Mattiscb1e0362021-04-06 17:07:42 -07004109 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004110
4111 pw.println();
4112 pw.println("bandwidth update requests (by uid):");
4113 pw.increaseIndent();
4114 synchronized (mBandwidthRequests) {
4115 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4116 pw.println("[" + mBandwidthRequests.keyAt(i)
4117 + "]: " + mBandwidthRequests.valueAt(i));
4118 }
4119 }
4120 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004121 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004122
James Mattiscb1e0362021-04-06 17:07:42 -07004123 pw.println();
4124 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4125 pw.increaseIndent();
4126 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004127 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004128 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004129
4130 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004131
4132 pw.println();
4133 pw.println("Permission Monitor:");
4134 pw.increaseIndent();
4135 mPermissionMonitor.dump(pw);
4136 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004137
4138 pw.println();
4139 pw.println("Legacy network activity:");
4140 pw.increaseIndent();
4141 mNetworkActivityTracker.dump(pw);
4142 pw.decreaseIndent();
Yang Sunca537d52024-01-19 12:53:50 +08004143
4144 pw.println();
4145 pw.println("Multicast routing supported: " +
4146 (mMulticastRoutingCoordinatorService != null));
The Android Open Source Project28527d22009-03-03 19:31:44 -08004147 }
4148
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004149 private void dumpNetworks(IndentingPrintWriter pw) {
4150 for (NetworkAgentInfo nai : networksSortedById()) {
4151 pw.println(nai.toString());
4152 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004153 pw.println("Nat464Xlat:");
4154 pw.increaseIndent();
4155 nai.dumpNat464Xlat(pw);
4156 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004157 pw.println(String.format(
4158 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4159 nai.numForegroundNetworkRequests(),
4160 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4161 nai.numBackgroundNetworkRequests(),
4162 nai.numNetworkRequests()));
4163 pw.increaseIndent();
4164 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4165 pw.println(nai.requestAt(i).toString());
4166 }
4167 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004168 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004169 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004170 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004171 pw.decreaseIndent();
4172 pw.decreaseIndent();
4173 }
4174 }
4175
James Mattis8b298a02021-06-01 22:34:04 -07004176 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4177 if (!mProfileNetworkPreferences.isEmpty()) {
4178 pw.println("Profile preferences:");
4179 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004180 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004181 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004182 }
James Mattis8b298a02021-06-01 22:34:04 -07004183 if (!mOemNetworkPreferences.isEmpty()) {
4184 pw.println("OEM preferences:");
4185 pw.increaseIndent();
4186 pw.println(mOemNetworkPreferences);
4187 pw.decreaseIndent();
4188 }
4189 if (!mMobileDataPreferredUids.isEmpty()) {
4190 pw.println("Mobile data preferred UIDs:");
4191 pw.increaseIndent();
4192 pw.println(mMobileDataPreferredUids);
4193 pw.decreaseIndent();
4194 }
James Mattis45d81842021-01-10 14:24:24 -08004195
James Mattis8b298a02021-06-01 22:34:04 -07004196 pw.println("Default requests:");
4197 pw.increaseIndent();
4198 dumpPerAppDefaultRequests(pw);
4199 pw.decreaseIndent();
4200 }
4201
4202 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004203 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4204 if (mDefaultRequest == defaultRequest) {
4205 continue;
4206 }
4207
James Mattis8b298a02021-06-01 22:34:04 -07004208 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4209 final String networkOutput;
4210 if (null == satisfier) {
4211 networkOutput = "null";
4212 } else if (mNoServiceNetwork.equals(satisfier)) {
4213 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004214 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004215 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004216 }
James Mattis8b298a02021-06-01 22:34:04 -07004217 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4218 ? "" : " asUid: " + defaultRequest.mAsUid;
4219 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4220 + defaultRequest.mPid + asUidString + "]";
4221 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4222 + " Preference order: " + defaultRequest.mPreferenceOrder
4223 + " Tracked UIDs: " + defaultRequest.getUids();
4224 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004225 }
4226 }
4227
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004228 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004229 NetworkRequestInfo[] infos = null;
4230 while (infos == null) {
4231 try {
4232 infos = requestsSortedById();
4233 } catch (ConcurrentModificationException e) {
4234 // mNetworkRequests should only be accessed from handler thread, except dump().
4235 // As dump() is never called in normal usage, it would be needlessly expensive
4236 // to lock the collection only for its benefit. Instead, retry getting the
4237 // requests if ConcurrentModificationException is thrown during dump().
4238 }
4239 }
4240 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004241 pw.println(nri.toString());
4242 }
4243 }
4244
Ken Chene6d511f2022-01-25 11:10:42 +08004245 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4246 boolean verbose) {
4247 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004248 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004249 } catch (ServiceSpecificException e) {
4250 pw.println(e.getMessage());
4251 } catch (IOException e) {
4252 loge("Dump BPF maps failed, " + e);
4253 }
4254 }
4255
Chalard Jean524f0b12021-10-25 21:11:56 +09004256 private void dumpAllRequestInfoLogsToLogcat() {
4257 try (PrintWriter logPw = new PrintWriter(new Writer() {
4258 @Override
4259 public void write(final char[] cbuf, final int off, final int len) {
4260 // This method is called with 0-length and 1-length arrays for empty strings
4261 // or strings containing only the DEL character.
4262 if (len <= 1) return;
4263 Log.e(TAG, new String(cbuf, off, len));
4264 }
4265 @Override public void flush() {}
4266 @Override public void close() {}
4267 })) {
4268 mNetworkRequestInfoLogs.dump(logPw);
4269 }
4270 }
4271
Hugo Benichia480ba52018-09-03 08:19:02 +09004272 /**
4273 * Return an array of all current NetworkAgentInfos sorted by network id.
4274 */
4275 private NetworkAgentInfo[] networksSortedById() {
4276 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004277 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004278 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004279 return networks;
4280 }
4281
4282 /**
4283 * Return an array of all current NetworkRequest sorted by request id.
4284 */
James Mattis258ea3c2020-11-15 15:04:40 -08004285 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004286 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004287 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004288 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004289 // Sort the array based off the NRI containing the min requestId in its requests.
4290 Arrays.sort(requests,
4291 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4292 Comparator.comparingInt(req -> req.requestId)).requestId
4293 )
4294 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004295 return requests;
4296 }
4297
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004298 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004299 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004300 if (officialNai != null && officialNai.equals(nai)) return true;
4301 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004302 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004303 " - " + nai);
4304 }
4305 return false;
4306 }
4307
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004308 private boolean isDisconnectRequest(Message msg) {
4309 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4310 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4311 return info.getState() == NetworkInfo.State.DISCONNECTED;
4312 }
4313
Robert Greenwalt2034b912009-08-12 16:08:25 -07004314 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004315 private class NetworkStateTrackerHandler extends Handler {
4316 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004317 super(looper);
4318 }
4319
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004320 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004321 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4322 final NetworkAgentInfo nai = arg.first;
4323 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004324 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004325 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004326 }
4327 return;
4328 }
4329
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004330 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004331 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004332 return;
4333 }
4334
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004335 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004336 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004337 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4338 if (!nai.respectsNcStructuralConstraints(proposed)) {
4339 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4340 + nai.networkCapabilities + " -> " + proposed);
4341 disconnectAndDestroyNetwork(nai);
4342 return;
4343 }
4344 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004345 final NetworkCapabilities sanitized =
4346 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004347 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004348 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004349 break;
4350 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004351 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004352 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004353 processLinkPropertiesFromAgent(nai, newLp);
4354 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004355 break;
4356 }
4357 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004358 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004359 updateNetworkInfo(nai, info);
4360 break;
4361 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004362 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4363 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004364 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004365 break;
4366 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004367 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004368 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004369 break;
4370 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004371 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004372 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004373 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004374 // Note that if the NAI had been connected, this would affect the
4375 // score, and therefore would require re-mixing the score and performing
4376 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004377 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004378 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4379 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004380 // Mark the network as temporarily accepting partial connectivity so that it
4381 // will be validated (and possibly become default) even if it only provides
4382 // partial internet access. Note that if user connects to partial connectivity
4383 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4384 // out of wifi coverage) and if the same wifi is available again, the device
4385 // will auto connect to this wifi even though the wifi has "no internet".
4386 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004387 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004388 break;
4389 }
junyulai011b1f12019-01-03 18:50:15 +08004390 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004391 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004392 break;
4393 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004394 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004395 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004396 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004397
4398 if (isLegacyLockdownNai(nai)
4399 && (underlying == null || underlying.size() != 1)) {
4400 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4401 + " must have exactly one underlying network: " + underlying);
4402 }
4403
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004404 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4405 nai.declaredUnderlyingNetworks = (underlying != null)
4406 ? underlying.toArray(new Network[0]) : null;
4407
4408 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4409 if (DBG) {
4410 log(nai.toShortString() + " changed underlying networks to "
4411 + Arrays.toString(nai.declaredUnderlyingNetworks));
4412 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004413 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004414 notifyIfacesChangedForNetworkStats();
4415 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004416 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004417 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004418 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4419 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4420 nai.teardownDelayMs = msg.arg1;
4421 } else {
4422 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4423 }
Chalard Jean550b5212021-03-05 23:07:53 +09004424 break;
4425 }
4426 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4427 nai.setLingerDuration((int) arg.second);
4428 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004429 }
Tyler Wear72388212021-09-09 14:49:02 -07004430 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4431 DscpPolicy policy = (DscpPolicy) arg.second;
4432 if (mDscpPolicyTracker != null) {
4433 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4434 }
4435 break;
4436 }
4437 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4438 if (mDscpPolicyTracker != null) {
4439 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4440 }
4441 break;
4442 }
4443 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4444 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004445 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004446 }
4447 break;
4448 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004449 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004450 if (!nai.everConnected()) {
4451 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4452 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004453 teardownUnneededNetwork(nai);
4454 break;
4455 }
4456
4457 if (nai.isDestroyed()) {
4458 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4459 + ", ignoring");
4460 break;
4461 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004462
4463 final int timeoutMs = (int) arg.second;
4464 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4465 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4466 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4467 }
4468
4469 // Marking a network awaiting replacement is used to ensure that any requests
4470 // satisfied by the network do not switch to another network until a
4471 // replacement is available or the wait for a replacement times out.
4472 // If the network is inactive (i.e., nascent or lingering), then there are no
4473 // such requests, and there is no point keeping it. Just tear it down.
4474 // Note that setLingerDuration(0) cannot be used to do this because the network
4475 // could be nascent.
4476 nai.clearInactivityState();
4477 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4478 Log.d(TAG, nai.toShortString()
4479 + " marked awaiting replacement is unneeded, tearing down instead");
4480 teardownUnneededNetwork(nai);
4481 break;
4482 }
4483
4484 Log.d(TAG, "Marking " + nai.toShortString()
4485 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4486 destroyNativeNetwork(nai);
4487
4488 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4489 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4490 // consider the fact that the network could already have disconnected or been
4491 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4492 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4493 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4494 mKeepaliveTracker.handleStopAllKeepalives(nai,
4495 SocketKeepalive.ERROR_INVALID_NETWORK);
4496
4497 nai.updateScoreForNetworkAgentUpdate();
4498 // This rematch is almost certainly not going to result in any changes, because
4499 // the destroyed flag is only just above the "current satisfier wins"
4500 // tie-breaker. But technically anything that affects scoring should rematch.
4501 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004502 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004503 break;
4504 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004505 }
4506 }
4507
4508 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004509 final int netId = msg.arg2;
4510 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004511 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004512 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004513 switch (msg.what) {
4514 default:
4515 return false;
lucasline117e2e2019-10-22 18:27:33 +08004516 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004517 if (nai == null) {
4518 break;
4519 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004520 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4521 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004522 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004523 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004524 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004525 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004526 if (probePrivateDnsCompleted) {
4527 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4528 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004529 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004530 }
4531 // Only show the notification when the private DNS is broken and the
4532 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004533 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004534 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4535 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004536 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004537 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4538 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4539 // private DNS is broken, it means this network is being reevaluated.
4540 // Either probing private DNS is not necessary any more or it hasn't been
4541 // done yet. In either case, the networkCapabilities should be updated to
4542 // reflect the new status.
4543 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004544 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004545 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004546 }
4547 break;
4548 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004549 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004550 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4551
Erik Kline31b4a9e2018-01-11 21:07:29 +09004552 if (nai == null) break;
4553
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004554 handleNetworkTested(nai, results.mTestResult,
4555 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004556 break;
4557 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004558 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004559 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004560 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004561 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004562 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004563 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004564 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4565 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004566 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004567 if (nai == null) {
4568 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4569 break;
4570 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004571 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004572 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004573 (PendingIntent) msg.obj,
4574 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004575 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004576 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004577 break;
4578 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004579 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004580 if (nai == null) break;
4581
Erik Kline9a62f012018-03-21 07:18:33 -07004582 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004583 break;
4584 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004585 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004586 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004587 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004588 break;
4589 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004590 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004591 return true;
4592 }
4593
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004594 private void handleNetworkTested(
4595 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004596 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4597 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004598 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004599
4600 // If there is any kind of working networking, then the NAI has been evaluated
4601 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4602 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004603 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004604 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004605 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4606 // any callback that receives onAvailable for that rematch receives an extra caps
4607 // callback. To prevent that, update the score in the agent so the updates below won't
4608 // see an update to both caps and score at the same time.
4609 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004610 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4611
he_won.hwang881307a2022-03-15 21:23:52 +09004612 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4613 // Assume the validation failure is due to a temporary failure after roaming
4614 // and ignore it. NetworkMonitor will continue to retry validation. If it
4615 // continues to fail after the block timeout expires, the network will be
4616 // marked unvalidated. If it succeeds, then validation state will not change.
4617 return;
4618 }
4619
Chalard Jean254bd162022-08-25 13:04:51 +09004620 final boolean wasValidated = nai.isValidated();
4621 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004622 final boolean wasPortal = nai.captivePortalDetected();
4623 nai.setPartialConnectivity(partial);
4624 nai.setCaptivePortalDetected(portal);
4625 nai.updateScoreForNetworkAgentUpdate();
4626 final boolean partialConnectivityChanged = (wasPartial != partial);
4627 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004628
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004629 if (DBG) {
4630 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4631 ? " with redirect to " + redirectUrl
4632 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004633 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004634 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004635 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004636 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004637 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004638 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004639 if (valid) {
4640 handleFreshlyValidatedNetwork(nai);
4641 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4642 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004643 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004644 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004645 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004646 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004647 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004648 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004649 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004650 NotificationType.PRIVATE_DNS_BROKEN);
4651 // If network becomes valid, the hasShownBroken should be reset for
4652 // that network so that the notification will be fired when the private
4653 // DNS is broken again.
4654 nai.networkAgentConfig.hasShownBroken = false;
4655 }
4656 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004657 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004658 } else if (portalChanged) {
4659 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004660 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004661 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4662 nai.onPreventAutomaticReconnect();
4663 teardownUnneededNetwork(nai);
4664 return;
4665 } else {
4666 updateCapabilitiesForNetwork(nai);
4667 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004668 } else if (becameEvaluated) {
4669 // If valid or partial connectivity changed, updateCapabilities* has
4670 // done the rematch.
4671 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004672 }
4673 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004674
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004675 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004676 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004677 nai.onValidationStatusChanged(
4678 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4679 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004680
4681 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004682 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004683 // immediately. Re-notify partial connectivity silently if no internet
4684 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004685 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004686 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004687 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4688 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004689 }
4690
Chalard Jean254bd162022-08-25 13:04:51 +09004691 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004692 handleNetworkUnvalidated(nai);
4693 }
4694 }
4695
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004696 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4697 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4698 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4699 // Do not avoid captive portal when network is wear proxy.
4700 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4701 }
4702
Calvin Ondada1452016-10-11 15:10:46 -07004703 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004704 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4705 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004706 }
4707
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004708 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4709 switch (msg.what) {
4710 default:
4711 return false;
4712 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4713 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4714 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4715 handleLingerComplete(nai);
4716 }
4717 break;
4718 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004719 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4720 handleNetworkAgentRegistered(msg);
4721 break;
4722 }
4723 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4724 handleNetworkAgentDisconnected(msg);
4725 break;
4726 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004727 }
4728 return true;
4729 }
4730
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004731 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004732 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004733 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004734 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004735 maybeHandleNetworkAgentMessage(msg);
4736 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004737 }
4738 }
4739
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004740 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004741 private final int mNetId;
4742 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004743
4744 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004745 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004746 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004747 }
4748
4749 @Override
4750 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4751 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004752 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004753 }
4754
4755 @Override
4756 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004757 // Legacy version of notifyNetworkTestedWithExtras.
4758 // Would only be called if the system has a NetworkStack module older than the
4759 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004760 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004761 }
4762
4763 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004764 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004765 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4766 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004767 final Message msg = mTrackerHandler.obtainMessage(
4768 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004769 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004770 new NetworkTestedResults(
4771 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004772 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004773
4774 // Invoke ConnectivityReport generation for this Network test event.
4775 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4776 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004777
Cody Kestingf1120be2020-08-03 18:01:40 -07004778 // NetworkMonitor reports the network validation result as a bitmask while
4779 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4780 // logical value for ConnectivityDiagnostics.
4781 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4782 p.result);
4783
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004784 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004785 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004786 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4787 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4788
Aaron Huang959d3642021-01-21 15:47:41 +08004789 ConnectivityReportEvent reportEvent =
4790 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4791 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004792 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004793 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004794 }
4795
4796 @Override
4797 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4798 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4799 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004800 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004801 }
4802
4803 @Override
lucasline117e2e2019-10-22 18:27:33 +08004804 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4805 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4806 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004807 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004808 }
4809
4810 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004811 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4812 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4813 EVENT_CAPPORT_DATA_CHANGED,
4814 0, mNetId, data));
4815 }
4816
4817 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004818 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004819 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004820 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004821
4822 final PendingIntent pendingIntent;
4823 // Only the system server can register notifications with package "android"
4824 final long token = Binder.clearCallingIdentity();
4825 try {
paulhu7746e4e2020-06-09 19:07:03 +08004826 pendingIntent = PendingIntent.getBroadcast(
4827 mContext,
4828 0 /* requestCode */,
4829 intent,
4830 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004831 } finally {
4832 Binder.restoreCallingIdentity(token);
4833 }
4834 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4835 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004836 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004837 }
4838
4839 @Override
4840 public void hideProvisioningNotification() {
4841 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004842 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004843 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004844
4845 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004846 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004847 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004848 }
4849
4850 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004851 public int getInterfaceVersion() {
4852 return this.VERSION;
4853 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004854
4855 @Override
4856 public String getInterfaceHash() {
4857 return this.HASH;
4858 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004859 }
4860
Cody Kestingf1120be2020-08-03 18:01:40 -07004861 /**
4862 * Converts the given NetworkMonitor-specific validation result bitmask to a
4863 * ConnectivityDiagnostics-specific validation result int.
4864 */
4865 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4866 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4867 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4868 }
4869 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4870 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4871 }
4872 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4873 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4874 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4875 }
4876
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004877 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004878 log("Data stall detected with methods: " + p.detectionMethod);
4879
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004880 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004881 int detectionMethod = 0;
4882 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4883 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4884 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4885 }
4886 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4887 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4888 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4889 p.tcpMetricsCollectionPeriodMillis);
4890 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004891 }
4892
Cody Kestingf53a0752020-04-15 12:33:28 -07004893 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004894 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004895 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004896
4897 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4898 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4899 // the cost of going through two handlers.
4900 mConnectivityDiagnosticsHandler.sendMessage(msg);
4901 }
4902
Cody Kestingb37958e2020-05-15 10:36:01 -07004903 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4904 return (p.detectionMethod & detectionMethod) != 0;
4905 }
4906
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004907 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4908 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004909 }
4910
Erik Klinea73af002018-06-26 18:53:43 +09004911 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4912 if (nai == null) return;
4913 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4914 // in order to restart a validation pass from within netd.
4915 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00004916 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004917 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004918 }
4919 }
4920
Erik Kline31b4a9e2018-01-11 21:07:29 +09004921 private void handlePrivateDnsSettingsChanged() {
4922 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4923
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004924 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004925 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004926 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004927 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4928 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004929 }
4930 }
4931
Erik Kline9a62f012018-03-21 07:18:33 -07004932 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4933 // Private DNS only ever applies to networks that might provide
4934 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004935 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004936
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004937 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004938 // schedule DNS resolutions. If a DNS resolution is required the
4939 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004940 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004941
4942 // With Private DNS bypass support, we can proceed to update the
4943 // Private DNS config immediately, even if we're in strict mode
4944 // and have not yet resolved the provider name into a set of IPs.
4945 updatePrivateDns(nai, cfg);
4946 }
4947
4948 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4949 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004950 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004951 }
4952
dalyk1720e542018-03-05 12:42:22 -05004953 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4954 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4955 if (nai == null) {
4956 return;
4957 }
4958 mDnsManager.updatePrivateDnsValidation(update);
4959 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4960 }
4961
paulhu7c0a2e62021-01-08 00:51:49 +08004962 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004963 int prefixLength) {
4964 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4965 if (nai == null) return;
4966
paulhu7c0a2e62021-01-08 00:51:49 +08004967 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4968 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004969
4970 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004971 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004972 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004973 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004974 prefixLength);
4975 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004976 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004977 return;
4978 }
4979 }
4980
Lorenzo Colittid523d142020-04-01 20:16:30 +09004981 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004982 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4983 }
4984
Hai Shalome58bdc62021-01-11 18:45:34 -08004985 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004986 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004987 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004988 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4989 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4990 }
4991
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004992 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004993 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004994 * @param nai the agent info to update
4995 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004996 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004997 */
junyulai2b6f0c22021-02-03 20:15:30 +08004998 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4999 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
5000 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005001 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08005002 // one lingered request, set inactive.
5003 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08005004 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08005005 if (DBG) log("Unsetting inactive " + nai.toShortString());
5006 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005007 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08005008 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005009 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08005010 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
5011 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005012 }
junyulai2b6f0c22021-02-03 20:15:30 +08005013 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005014 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005015 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005016 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005017 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05005018 }
5019
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005020 private void handleNetworkAgentRegistered(Message msg) {
5021 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
5022 if (!mNetworkAgentInfos.contains(nai)) {
5023 return;
5024 }
5025
5026 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
5027 if (VDBG) log("NetworkAgent registered");
5028 } else {
5029 loge("Error connecting NetworkAgent");
5030 mNetworkAgentInfos.remove(nai);
5031 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005032 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005033 synchronized (mNetworkForNetId) {
5034 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005035 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005036 mNetIdManager.releaseNetId(nai.network.getNetId());
5037 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09005038 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005039 }
5040 }
5041 }
Paul Jensend5f53392014-11-25 15:26:53 -05005042
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005043 @VisibleForTesting
5044 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09005045 // The feature of creating the networks immediately was slated for U, but race conditions
5046 // detected late required this was flagged off.
5047 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
5048 // in NetworkAgentTest.
5049 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005050 }
5051
5052 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
5053 @NonNull NetworkInfo.State state) {
5054 if (nai.isCreated()) return false;
5055 if (state == NetworkInfo.State.CONNECTED) return true;
5056 if (state != NetworkInfo.State.CONNECTING) {
5057 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09005058 if (shouldCreateNetworksImmediately()) {
5059 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
5060 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005061 return false;
5062 }
5063 return nai.isVPN() || shouldCreateNetworksImmediately();
5064 }
5065
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005066 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09005067 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005068 }
5069
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005070 @VisibleForTesting
5071 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09005072 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09005073 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005074
5075 // If the network never roamed, return false. The check below is not sufficient if time
5076 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
5077 if (nai.lastRoamTime == 0) return false;
5078
he_won.hwang881307a2022-03-15 21:23:52 +09005079 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
5080 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005081 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09005082 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09005083 final long currentTimeMs = SystemClock.elapsedRealtime();
5084 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09005085 if (timeSinceLastRoam <= blockTimeOut) {
5086 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
5087 return true;
5088 }
5089 }
5090 return false;
5091 }
5092
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005093 private void handleNetworkAgentDisconnected(Message msg) {
5094 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07005095 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005096 }
5097
Chalard Jeand9fffc32018-05-11 20:19:20 +09005098 // Destroys a network, remove references to it from the internal state managed by
5099 // ConnectivityService, free its interfaces and clean up.
5100 // Must be called on the Handler thread.
5101 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005102 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07005103
5104 if (!mNetworkAgentInfos.contains(nai)) return;
5105
Chalard Jeand9fffc32018-05-11 20:19:20 +09005106 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09005107 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005108 }
lucaslinb25c9a62019-02-12 15:30:13 +08005109 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005110 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005111 // A network agent has disconnected.
5112 // TODO - if we move the logic to the network agent (have them disconnect
5113 // because they lost all their requests or because their score isn't good)
5114 // then they would disconnect organically, report their new state and then
5115 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08005116 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005117 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5118 null, null);
5119 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005120 final boolean wasDefault = isDefaultNetwork(nai);
5121 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005122 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005123 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005124 if (mTrackMultiNetworkActivities) {
5125 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5126 // the network becomes no longer the default network.
5127 mNetworkActivityTracker.removeDataActivityTracking(nai);
5128 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005129 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005130 // If this was a local network forwarded to some upstream, or if some local network was
5131 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005132 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005133 // If this is a local network with an upstream selector, remove the associated network
5134 // request.
5135 if (nai.isLocalNetwork()) {
5136 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5137 if (null != selector) {
5138 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5139 }
5140 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005141 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5142 // by other networks that are already connected. Perhaps that can be done by
5143 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5144 // of rematchAllNetworksAndRequests
5145 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005146 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005147
5148 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005149 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5150 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005151 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005152 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005153 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005154 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005155 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005156 synchronized (mNetworkForNetId) {
5157 // Remove the NetworkAgent, but don't mark the netId as
5158 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005159 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005160 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005161 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005162 // Update allowed network lists in netd. This should be called after removing nai
5163 // from mNetworkAgentInfos.
5164 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005165 // Remove all previously satisfied requests.
5166 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005167 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005168 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005169 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005170 if (currentNetwork != null
5171 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005172 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005173 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5174 // rematch not to keep disconnected agents instead of setting it here ; this
5175 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005176 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005177 for (final NetworkOfferInfo noi : mNetworkOffers) {
5178 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005179 }
James Mattise3ef1912020-12-20 11:09:58 -08005180
Chalard Jean5b409c72021-02-04 13:12:59 +09005181 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005182 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005183 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005184 ensureNetworkTransitionWakelock(nai.toShortString());
5185 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005186 }
5187 }
junyulai2b6f0c22021-02-03 20:15:30 +08005188 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005189 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005190 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005191 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005192 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005193 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005194 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005195
Aaron Huang9fe47be2021-06-08 13:11:45 +08005196 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5197 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5198 // not called by the rematch in this case. This is because the code above unset
5199 // this network from the default request's satisfier, and that is what the rematch
5200 // is using as its source data to know what the old satisfier was. So as far as the
5201 // rematch above is concerned, the old default network was null.
5202 // Therefore if there is no new default, the default network was null and is still
5203 // null, thus there was no change so makeDefault() is not called. So if the old
5204 // network had a proxy and there is no new default, the proxy tracker should be told
5205 // that there is no longer a default proxy.
5206 // Strictly speaking this is not essential because having a proxy setting when
5207 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5208 mProxyTracker.setDefaultProxy(null);
5209 }
5210
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005211 // Immediate teardown.
5212 if (nai.teardownDelayMs == 0) {
5213 destroyNetwork(nai);
5214 return;
5215 }
5216
5217 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005218 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305219 try {
5220 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5221 } catch (RemoteException e) {
5222 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5223 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005224 }
5225 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5226 }
5227
5228 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005229 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005230 // Tell netd to clean up the configuration for this network
5231 // (routing rules, DNS, etc).
5232 // This may be slow as it requires a lot of netd shelling out to ip and
5233 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005234 // after we've rematched networks with requests (which might change the default
5235 // network or service a new request from an app), so network traffic isn't interrupted
5236 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005237 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005238 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005239 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005240 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5241 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5242 // false if the network was never created.
5243 // TODO: delete when S is no longer supported.
5244 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005245 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005246 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005247 }
5248
Chalard Jean1e4c2182023-10-06 18:45:53 +09005249 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005250 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005251 // Step 1 : maybe this network was the upstream for one or more local networks.
5252 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5253 if (!local.isLocalNetwork()) continue;
5254 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5255 if (null == selector) continue;
5256 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5257 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5258 // called after removing all associated NRIs from mNetworkRequests.
5259 if (null == nri) continue;
5260 final NetworkAgentInfo satisfier = nri.getSatisfier();
5261 if (disconnecting != satisfier) continue;
5262 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005263 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5264 // correctly contains null as an upstream.
5265 if (sendCallbacks) {
5266 nri.setSatisfier(null, null);
5267 notifyNetworkCallbacks(local,
5268 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5269 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005270 }
5271
5272 // Step 2 : maybe this is a local network that had an upstream.
5273 if (!disconnecting.isLocalNetwork()) return;
5274 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5275 if (null == selector) return;
5276 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5277 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5278 // is called after removing all associated NRIs from mNetworkRequests.
5279 if (null == nri) return;
5280 final NetworkAgentInfo satisfier = nri.getSatisfier();
5281 if (null == satisfier) return;
5282 removeLocalNetworkUpstream(disconnecting, satisfier);
5283 }
5284
5285 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5286 @NonNull final NetworkAgentInfo upstream) {
5287 try {
Yang Sun29037f62023-12-04 10:31:58 +08005288 final String localNetworkInterfaceName = localAgent.linkProperties.getInterfaceName();
5289 final String upstreamNetworkInterfaceName = upstream.linkProperties.getInterfaceName();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005290 mRoutingCoordinatorService.removeInterfaceForward(
Yang Sun29037f62023-12-04 10:31:58 +08005291 localNetworkInterfaceName,
5292 upstreamNetworkInterfaceName);
5293 disableMulticastRouting(localNetworkInterfaceName, upstreamNetworkInterfaceName);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005294 } catch (RemoteException e) {
5295 loge("Couldn't remove interface forward for "
5296 + localAgent.linkProperties.getInterfaceName() + " to "
5297 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5298 }
5299 }
5300
Ken Chen6df7a902021-04-09 15:08:42 +08005301 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005302 try {
5303 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005304 final NativeNetworkConfig config;
5305 if (nai.isVPN()) {
5306 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005307 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005308 return false;
5309 }
5310 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5311 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005312 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005313 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005314 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005315 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005316 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5317 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005318 getNetworkPermission(nai.networkCapabilities),
5319 false /* secure */,
5320 VpnManager.TYPE_VPN_NONE,
5321 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005322 }
Ken Chen6df7a902021-04-09 15:08:42 +08005323 mNetd.networkCreate(config);
5324 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005325 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5326 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005327 return true;
5328 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005329 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005330 return false;
5331 }
5332 }
5333
Ken Chen6df7a902021-04-09 15:08:42 +08005334 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005335 if (mDscpPolicyTracker != null) {
5336 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5337 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005338 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005339 // the interface is going to go away. Don't send the callbacks however ; if the network
5340 // was is being disconnected the callbacks have already been sent, and if it is being
5341 // destroyed pending replacement they will be sent when it is disconnected.
5342 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005343 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005344 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005345 } catch (RemoteException | ServiceSpecificException e) {
5346 loge("Exception destroying network(networkDestroy): " + e);
5347 }
5348 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005349 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005350 } catch (RemoteException | ServiceSpecificException e) {
5351 loge("Exception destroying network: " + e);
5352 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005353 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5354 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5355 // gets created, could add data to DnsManager data structures that will never get deleted.
5356 mDnsManager.removeNetwork(nai.network);
5357
5358 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005359 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005360 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5361 }
5362
Chalard Jean254bd162022-08-25 13:04:51 +09005363 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005364 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005365 }
5366
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005367 // If this method proves to be too slow then we can maintain a separate
5368 // pendingIntent => NetworkRequestInfo map.
5369 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5370 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005371 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5372 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5373 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005374 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005375 return entry.getValue();
5376 }
5377 }
5378 return null;
5379 }
5380
Chalard Jean524f0b12021-10-25 21:11:56 +09005381 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005382 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005383 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5384 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5385 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5386 // bug is fixed.
5387 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005388 throw new IllegalStateException("This NRI is already registered. New : " + nri
5389 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005390 }
5391 }
5392 }
5393 }
5394
Chalard Jeanac9ace02022-01-26 16:54:05 +09005395 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5396 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005397 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005398 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005399 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005400 }
5401 return false;
5402 }
5403
James Mattisf7027322020-12-13 16:28:14 -08005404 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005405 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005406 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5407 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5408 final NetworkRequestInfo existingRequest =
5409 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005410 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005411 if (DBG) {
5412 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5413 + nri.mRequests.get(0) + " because their intents matched.");
5414 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005415 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005416 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005417 }
Erik Kline05f2b402015-04-30 12:58:40 +09005418 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005419 }
5420
James Mattisf7027322020-12-13 16:28:14 -08005421 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005422 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005423 }
5424
James Mattis3ce3d3c2021-02-09 18:18:28 -08005425 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005426 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005427 for (final NetworkRequestInfo nri : nris) {
5428 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005429 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005430 for (final NetworkRequest req : nri.mRequests) {
5431 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005432 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005433 if (req.isListen()) {
5434 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5435 if (req.networkCapabilities.hasSignalStrength()
5436 && network.satisfiesImmutableCapabilitiesOf(req)) {
5437 updateSignalStrengthThresholds(network, "REGISTER", req);
5438 }
James Mattisf7027322020-12-13 16:28:14 -08005439 }
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005440 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5441 mNetworkRequestStateStatsMetrics.onNetworkRequestReceived(req);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005442 }
5443 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005444
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005445 // If this NRI has a satisfier already, it is replacing an older request that
5446 // has been removed. Track it.
5447 final NetworkRequest activeRequest = nri.getActiveRequest();
5448 if (null != activeRequest) {
5449 // If there is an active request, then for sure there is a satisfier.
5450 nri.getSatisfier().addRequest(activeRequest);
5451 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005452 }
James Mattisf7027322020-12-13 16:28:14 -08005453
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005454 if (mFlags.noRematchAllRequestsOnRegister()) {
5455 rematchNetworksAndRequests(nris);
5456 } else {
5457 rematchAllNetworksAndRequests();
5458 }
James Mattis45d81842021-01-10 14:24:24 -08005459
Chalard Jean0354d8c2021-01-12 10:58:56 +09005460 // Requests that have not been matched to a network will not have been sent to the
5461 // providers, because the old satisfier and the new satisfier are the same (null in this
5462 // case). Send these requests to the providers.
5463 for (final NetworkRequestInfo nri : nris) {
5464 for (final NetworkOfferInfo noi : mNetworkOffers) {
5465 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005466 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005467 }
5468 }
5469
James Mattisf7027322020-12-13 16:28:14 -08005470 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5471 final int callingUid) {
5472 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005473 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005474 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5475 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5476 handleReleaseNetworkRequest(
5477 nri.mRequests.get(0),
5478 callingUid,
5479 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005480 }
5481 }
5482
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005483 // Determines whether the network is the best (or could become the best, if it validated), for
5484 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5485 // on the value of reason:
5486 //
5487 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5488 // then it should be torn down.
5489 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5490 // then it should be lingered.
5491 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005492 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005493
Chalard Jean254bd162022-08-25 13:04:51 +09005494 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005495 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5496 return false;
5497 }
5498
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005499 final int numRequests;
5500 switch (reason) {
5501 case TEARDOWN:
5502 numRequests = nai.numRequestNetworkRequests();
5503 break;
5504 case LINGER:
5505 numRequests = nai.numForegroundNetworkRequests();
5506 break;
5507 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005508 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005509 return true;
5510 }
5511
Chalard Jean947acd42021-03-08 22:29:27 +09005512 if (numRequests > 0) return false;
5513
Paul Jensende49eb12015-06-25 15:30:08 -04005514 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005515 if (reason == UnneededFor.LINGER
5516 && !nri.isMultilayerRequest()
5517 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005518 // Background requests don't affect lingering.
5519 continue;
5520 }
5521
James Mattis3d229892020-11-16 16:46:28 -08005522 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005523 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005524 }
5525 }
Paul Jensende49eb12015-06-25 15:30:08 -04005526 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005527 }
5528
James Mattis3d229892020-11-16 16:46:28 -08005529 private boolean isNetworkPotentialSatisfier(
5530 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005531 // While destroyed network sometimes satisfy requests (including occasionally newly
5532 // satisfying requests), *potential* satisfiers are networks that might beat a current
5533 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5534 // because it's never a good idea to keep a destroyed network in case it validates.
5535 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5536 // candidate after it's been replaced by another unvalidated network.
5537 if (candidate.isDestroyed()) return false;
5538 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005539 // request, return immediately. For multilayer requests, check to see if any of the
5540 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005541 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5542 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005543 return false;
5544 }
5545 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005546 // This multilayer listen request is satisfied therefore no further requests need to be
5547 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005548 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005549 return false;
5550 }
James Mattis3d229892020-11-16 16:46:28 -08005551 // As non-multilayer listen requests have already returned, the below would only happen
5552 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005553 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005554 continue;
5555 }
Chalard Jean80685f42023-10-30 18:31:27 +09005556 // If there is hope for this network might validate and subsequently become the best
5557 // network for that request, then it is needed. Note that this network can't already
5558 // be the best for this request, or it would be the current satisfier, and therefore
5559 // there would be no need to call this method to find out if it is a *potential*
5560 // satisfier ("unneeded", the only caller, only calls this if this network currently
5561 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005562 if (candidate.satisfies(req)) {
5563 // As soon as a network is found that satisfies a request, return. Specifically for
5564 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5565 // is important so as to not evaluate lower priority requests further in
5566 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005567 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5568 ? nri.getSatisfier() : null;
5569 // Note that this catches two important cases:
5570 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5571 // is currently satisfying the request. This is desirable when
5572 // cellular ends up validating but WiFi does not.
5573 // 2. Unvalidated WiFi will not be reaped when validated cellular
5574 // is currently satisfying the request. This is desirable when
5575 // WiFi ends up validating and out scoring cellular.
5576 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005577 }
5578 }
5579
5580 return false;
5581 }
5582
Erik Kline0c04b742016-07-07 16:50:58 +09005583 private NetworkRequestInfo getNriForAppRequest(
5584 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005585 // Looking up the app passed param request in mRequests isn't possible since it may return
5586 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5587 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005588 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5589 // to avoid potential race conditions when validating a package->uid mapping when sending
5590 // the callback on the very low-chance that an application shuts down prior to the callback
5591 // being sent.
5592 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5593 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005594
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005595 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005596 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005597 log(String.format("UID %d attempted to %s for unowned request %s",
5598 callingUid, requestedOperation, nri));
5599 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005600 }
Erik Kline0c04b742016-07-07 16:50:58 +09005601 }
5602
5603 return nri;
5604 }
5605
James Mattisf7027322020-12-13 16:28:14 -08005606 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5607 final String callingMethod) {
5608 if (nri.isMultilayerRequest()) {
5609 throw new IllegalStateException(
5610 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005611 }
5612 }
5613
James Mattisf7027322020-12-13 16:28:14 -08005614 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005615 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005616 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5617 // single NetworkRequest and thus does not apply to multilayer requests.
5618 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5619 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005620 return;
5621 }
James Mattis2516da32021-01-31 17:06:19 -08005622 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005623 return;
5624 }
James Mattisf7027322020-12-13 16:28:14 -08005625 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5626 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005627 }
5628 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005629 callCallbackForRequest(
5630 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005631 }
5632
James Mattisf7027322020-12-13 16:28:14 -08005633 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5634 final int callingUid,
5635 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005636 final NetworkRequestInfo nri =
5637 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5638 if (nri == null) {
5639 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005640 }
James Mattisf7027322020-12-13 16:28:14 -08005641 if (VDBG || (DBG && request.isRequest())) {
5642 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005643 }
5644 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005645 if (callOnUnavailable) {
5646 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5647 }
Erik Kline155a59a2015-11-25 12:49:38 +09005648 }
Erik Kline0c04b742016-07-07 16:50:58 +09005649
James Mattisa076c532020-12-02 14:12:41 -08005650 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005651 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005652 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005653 if (null == mNetworkRequests.remove(req)) {
5654 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5655 continue;
5656 }
James Mattisa076c532020-12-02 14:12:41 -08005657 if (req.isListen()) {
5658 removeListenRequestFromNetworks(req);
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005659 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5660 mNetworkRequestStateStatsMetrics.onNetworkRequestRemoved(req);
James Mattisa076c532020-12-02 14:12:41 -08005661 }
5662 }
James Mattis8f036802021-06-20 16:26:01 -07005663 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005664 if (mDefaultNetworkRequests.remove(nri)) {
5665 // If this request was one of the defaults, then the UID rules need to be updated
5666 // WARNING : if the app(s) for which this network request is the default are doing
5667 // traffic, this will kill their connected sockets, even if an equivalent request
5668 // is going to be reinstated right away ; unconnected traffic will go on the default
5669 // until the new default is set, which will happen very soon.
5670 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5671 // remove ranges for those requests that won't have a replacement
5672 final NetworkAgentInfo satisfier = nri.getSatisfier();
5673 if (null != satisfier) {
5674 try {
paulhu0e79d952021-06-09 16:11:35 +08005675 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5676 satisfier.network.getNetId(),
5677 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005678 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005679 } catch (RemoteException e) {
5680 loge("Exception setting network preference default network", e);
5681 }
5682 }
5683 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005684
Junyu Lai00d92df2022-07-05 11:01:52 +08005685 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005686 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005687 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005688
5689 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005690 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005691 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005692 }
5693 }
5694
Chalard Jean0354d8c2021-01-12 10:58:56 +09005695 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5696 // needed for this offer.
5697 for (final NetworkOfferInfo noi : mNetworkOffers) {
5698 for (final NetworkRequest req : nri.mRequests) {
5699 if (req.isRequest() && noi.offer.neededFor(req)) {
5700 noi.offer.onNetworkUnneeded(req);
5701 }
5702 }
5703 }
James Mattisa076c532020-12-02 14:12:41 -08005704 }
5705
James Mattis3ce3d3c2021-02-09 18:18:28 -08005706 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5707 for (final NetworkRequestInfo nri : nris) {
5708 if (mDefaultRequest == nri) {
5709 // Make sure we never remove the default request.
5710 continue;
5711 }
5712 handleRemoveNetworkRequest(nri);
5713 }
5714 }
5715
James Mattisa076c532020-12-02 14:12:41 -08005716 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5717 // listens don't have a singular affected Network. Check all networks to see
5718 // if this listen request applies and remove it.
5719 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5720 nai.removeRequest(req.requestId);
5721 if (req.networkCapabilities.hasSignalStrength()
5722 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5723 updateSignalStrengthThresholds(nai, "RELEASE", req);
5724 }
5725 }
5726 }
5727
5728 /**
5729 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5730 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5731 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5732 */
5733 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5734 boolean wasKept = false;
5735 final NetworkAgentInfo nai = nri.getSatisfier();
5736 if (nai != null) {
5737 final int requestLegacyType = nri.getActiveRequest().legacyType;
5738 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5739 nai.removeRequest(nri.getActiveRequest().requestId);
5740 if (VDBG || DDBG) {
5741 log(" Removing from current network " + nai.toShortString()
5742 + ", leaving " + nai.numNetworkRequests() + " requests.");
5743 }
5744 // If there are still lingered requests on this network, don't tear it down,
5745 // but resume lingering instead.
5746 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005747 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005748 notifyNetworkLosing(nai, now);
5749 }
5750 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5751 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5752 teardownUnneededNetwork(nai);
5753 } else {
5754 wasKept = true;
5755 }
James Mattisa076c532020-12-02 14:12:41 -08005756 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5757 // Went from foreground to background.
5758 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005759 }
5760
Erik Kline0c04b742016-07-07 16:50:58 +09005761 // Maintain the illusion. When this request arrived, we might have pretended
5762 // that a network connected to serve it, even though the network was already
5763 // connected. Now that this request has gone away, we might have to pretend
5764 // that the network disconnected. LegacyTypeTracker will generate that
5765 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005766 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005767 boolean doRemove = true;
5768 if (wasKept) {
5769 // check if any of the remaining requests for this network are for the
5770 // same legacy type - if so, don't remove the nai
5771 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5772 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005773 if (otherRequest.legacyType == requestLegacyType
5774 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005775 if (DBG) log(" still have other legacy request - leaving");
5776 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005777 }
5778 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005779 }
5780
Erik Kline0c04b742016-07-07 16:50:58 +09005781 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005782 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005783 }
5784 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005785 }
5786 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005787
Junyu Lai00d92df2022-07-05 11:01:52 +08005788 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai71b51532024-02-01 10:39:01 +08005789 return hasAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005790 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5791 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5792 }
5793
Lorenzo Colittid6459092016-07-04 12:55:44 +09005794 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005795 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005796 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005797 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005798 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005799 }
5800
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005801 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005802 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5803 enforceNetworkStackSettingsOrSetup();
5804 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5805 encodeBool(accept), encodeBool(always), network));
5806 }
5807
5808 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005809 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005810 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005811 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5812 }
5813
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005814 @Override
5815 public void setTestAllowBadWifiUntil(long timeMs) {
5816 enforceSettingsPermission();
5817 if (!Build.isDebuggable()) {
5818 throw new IllegalStateException("Does not support in non-debuggable build");
5819 }
5820
5821 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5822 throw new IllegalArgumentException("It should not exceed "
5823 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5824 }
5825
5826 mHandler.sendMessage(
5827 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5828 }
5829
chiachangwange0192a72023-02-06 13:25:01 +00005830 @Override
5831 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5832 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005833
5834 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5835 throw new IllegalArgumentException("Argument should not exceed "
5836 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5837 }
5838
5839 mHandler.sendMessage(
5840 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5841 }
5842
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005843 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5844 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5845 " accept=" + accept + " always=" + always);
5846
5847 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5848 if (nai == null) {
5849 // Nothing to do.
5850 return;
5851 }
5852
Chalard Jean254bd162022-08-25 13:04:51 +09005853 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005854 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005855 return;
5856 }
5857
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005858 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005859 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005860 }
5861
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005862 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5863 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005864 // If network becomes partial connectivity and user already accepted to use this
5865 // network, we should respect the user's option and don't need to popup the
5866 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005867 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005868 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005869 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005870 }
5871
5872 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005873 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005874 }
5875
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005876 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005877 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005878 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005879 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005880 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005881 }
5882
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005883 }
5884
lucaslin2240ef62019-03-12 13:08:03 +08005885 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5886 boolean always) {
5887 if (DBG) {
5888 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5889 + " always=" + always);
5890 }
5891
5892 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5893 if (nai == null) {
5894 // Nothing to do.
5895 return;
5896 }
5897
Chalard Jean254bd162022-08-25 13:04:51 +09005898 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005899 // The network validated while the dialog box was up. Take no action.
5900 return;
5901 }
5902
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005903 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5904 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005905 }
5906
5907 // TODO: Use the current design or save the user choice into IpMemoryStore.
5908 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005909 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005910 }
5911
5912 if (!accept) {
5913 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005914 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005915 // Tear down the network.
5916 teardownUnneededNetwork(nai);
5917 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005918 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5919 // result in a partial connectivity result which will be processed by
5920 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005921 //
5922 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5923 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005924 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005925 }
5926 }
5927
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005928 private void handleSetAvoidUnvalidated(Network network) {
5929 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005930 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005931 // Nothing to do. The network either disconnected or revalidated.
5932 return;
5933 }
Chalard Jean254bd162022-08-25 13:04:51 +09005934 if (0L == nai.getAvoidUnvalidated()) {
5935 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005936 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005937 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005938 }
5939 }
5940
Chalard Jean5fb43c72022-09-08 19:03:14 +09005941 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005942 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005943 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005944 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005945 }
5946
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005947 @Override
5948 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005949 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005950 mHandler.post(() -> {
5951 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5952 if (nai == null) return;
5953 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005954 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005955 });
5956 }
5957
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005958 /**
5959 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5960 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005961 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005962 * @param appExtras Bundle to use as intent extras for the captive portal application.
5963 * Must be treated as opaque to avoid preventing the captive portal app to
5964 * update its arguments.
5965 */
5966 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005967 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005968 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5969 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005970
5971 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5972 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005973 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5974 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005975 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5976
lucaslin75ff7022020-12-17 04:14:35 +08005977 final long token = Binder.clearCallingIdentity();
5978 try {
5979 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5980 } finally {
5981 Binder.restoreCallingIdentity(token);
5982 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005983 }
5984
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005985 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5986 private final Network mNetwork;
5987
5988 private CaptivePortalImpl(Network network) {
5989 mNetwork = network;
5990 }
5991
5992 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005993 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005994 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5995 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005996 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5997 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5998 // Since the network will be disconnected, skip notifying NetworkMonitor
5999 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006000 }
6001
Chiachang Wang938bfba2020-01-09 13:50:55 +08006002 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006003 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006004 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006005 }
6006
6007 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08006008 public void appRequest(final int request) {
6009 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
6010 if (nm == null) return;
6011
6012 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Junyu Lai71b51532024-02-01 10:39:01 +08006013 hasNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006014 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08006015 }
6016 }
6017
6018 @Nullable
6019 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
6020 // getNetworkAgentInfoForNetwork is thread-safe
6021 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6022 if (nai == null) return null;
6023
6024 // nai.networkMonitor() is thread-safe
6025 return nai.networkMonitor();
6026 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006027 }
6028
Hugo Benichic9048bc2016-09-14 23:23:08 +00006029 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006030 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09006031 }
6032
Chalard Jean020b93a2022-09-01 13:20:14 +09006033 private boolean activelyPreferBadWifi() {
6034 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
6035 }
6036
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09006037 /**
6038 * Return whether the device should maintain continuous, working connectivity by switching away
6039 * from WiFi networks having no connectivity.
6040 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
6041 */
6042 public boolean shouldAvoidBadWifi() {
Junyu Lai71b51532024-02-01 10:39:01 +08006043 if (!hasNetworkStackPermission()) {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09006044 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
6045 }
6046 return avoidBadWifi();
6047 }
6048
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006049 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09006050 ensureRunningOnConnectivityServiceThread();
6051 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09006052 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006053 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09006054 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09006055 if (avoidBadWifi) {
6056 // If the device is now avoiding bad wifi, remove notifications that might have
6057 // been put up when the device didn't.
6058 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
6059 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006060 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09006061 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
6062 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
6063 for (final NetworkOfferInfo noi : offersToUpdate) {
6064 updateOfferScore(noi.offer);
6065 }
Chalard Jean020b93a2022-09-01 13:20:14 +09006066 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09006067 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006068 }
6069
Erik Kline95ecfee2016-10-02 18:02:14 +09006070 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006071 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006072 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006073 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006074 if (!configRestrict) {
6075 pw.println("Bad Wi-Fi avoidance: unrestricted");
6076 return;
6077 }
6078
6079 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
6080 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09006081 pw.println("Config restrict: " + configRestrict);
6082 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006083
Chalard Jeane0fdea32022-09-14 21:44:22 +09006084 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006085 String description;
6086 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09006087 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006088 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006089 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006090 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006091 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006092 description = "avoid";
6093 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09006094 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006095 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09006096 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00006097
6098 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
6099 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09006100 if (null == configValue) {
6101 description = "unset";
6102 } else if (configValue) {
6103 description = "force true";
6104 } else {
6105 description = "force false";
6106 }
6107 pw.println("Actively prefer bad wifi conf: " + description);
6108 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006109 pw.println("Network overrides:");
6110 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09006111 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09006112 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09006113 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006114 }
6115 }
6116 pw.decreaseIndent();
6117 pw.decreaseIndent();
6118 }
6119
paulhu7746e4e2020-06-09 19:07:03 +08006120 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
6121 // unify the method.
6122 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
6123 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
6124 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
6125 return settingsComponent != null
6126 ? settingsComponent.getPackageName() : "com.android.settings";
6127 }
6128
lucaslinb1e8e382019-01-24 15:55:30 +08006129 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006130 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006131 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006132 switch (type) {
6133 case NO_INTERNET:
6134 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006135 // High priority because it is only displayed for explicitly selected networks.
6136 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006137 break;
lucasline117e2e2019-10-22 18:27:33 +08006138 case PRIVATE_DNS_BROKEN:
6139 action = Settings.ACTION_WIRELESS_SETTINGS;
6140 // High priority because we should let user know why there is no internet.
6141 highPriority = true;
6142 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006143 case LOST_INTERNET:
6144 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006145 // High priority because it could help the user avoid unexpected data usage.
6146 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006147 break;
lucaslin2240ef62019-03-12 13:08:03 +08006148 case PARTIAL_CONNECTIVITY:
6149 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006150 // Don't bother the user with a high-priority notification if the network was not
6151 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006152 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006153 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006154 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006155 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006156 return;
6157 }
6158
6159 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006160 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006161 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006162 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006163 // Some OEMs have their own Settings package. Thus, need to get the current using
6164 // Settings package name instead of just use default name "com.android.settings".
6165 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6166 intent.setClassName(settingsPkgName,
6167 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006168 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006169
paulhu2af50222020-10-11 22:52:27 +08006170 PendingIntent pendingIntent = PendingIntent.getActivity(
6171 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006172 0 /* requestCode */,
6173 intent,
paulhu2af50222020-10-11 22:52:27 +08006174 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006175
Serik Beketayevec8ad212020-12-07 22:43:07 -08006176 mNotifier.showNotification(
6177 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006178 }
6179
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006180 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6181 // Don't prompt if the network is validated, and don't prompt on captive portals
6182 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006183 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006184 return false;
6185 }
6186
6187 // If a network has partial connectivity, always prompt unless the user has already accepted
6188 // partial connectivity and selected don't ask again. This ensures that if the device
6189 // automatically connects to a network that has partial Internet access, the user will
6190 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006191 // because we have prompted them.
6192 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006193 return true;
6194 }
6195
6196 // If a network has no Internet access, only prompt if the network was explicitly selected
6197 // and if the user has not already told us to use the network regardless of whether it
6198 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006199 if (nai.networkAgentConfig.explicitlySelected
6200 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006201 return true;
6202 }
6203
6204 return false;
6205 }
6206
Chalard Jean5fb43c72022-09-08 19:03:14 +09006207 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6208 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006209
Chalard Jean5fb43c72022-09-08 19:03:14 +09006210 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6211 if (null == nai) return;
6212
6213 if (nai.setEvaluated()) {
6214 // If setEvaluated() returned true, the network never had any form of connectivity.
6215 // This may have an impact on request matching if bad WiFi avoidance is off and the
6216 // network was found not to have Internet access.
6217 nai.updateScoreForNetworkAgentUpdate();
6218 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006219
6220 // Also, if this is WiFi and it should be preferred actively, now is the time to
6221 // prompt the user that they walked past and connected to a bad WiFi.
6222 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6223 && !avoidBadWifi()
6224 && activelyPreferBadWifi()) {
6225 // The notification will be removed if the network validates or disconnects.
6226 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6227 return;
6228 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006229 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006230
Chalard Jean5fb43c72022-09-08 19:03:14 +09006231 if (!shouldPromptUnvalidated(nai)) return;
6232
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006233 // Stop automatically reconnecting to this network in the future. Automatically connecting
6234 // to a network that provides no or limited connectivity is not useful, because the user
6235 // cannot use that network except through the notification shown by this method, and the
6236 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006237 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006238
Chalard Jean254bd162022-08-25 13:04:51 +09006239 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006240 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006241 } else {
6242 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6243 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006244 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006245
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006246 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6247 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006248 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006249
lucaslin2240ef62019-03-12 13:08:03 +08006250 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6251 return;
6252 }
6253
6254 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006255 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006256 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006257 }
6258
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006259 @Override
6260 public int getMultipathPreference(Network network) {
6261 enforceAccessPermission();
6262
6263 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006264 if (nai != null && nai.networkCapabilities
6265 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006266 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6267 }
6268
Aaron Huang9a57acf2020-12-08 10:03:29 +08006269 final NetworkPolicyManager netPolicyManager =
6270 mContext.getSystemService(NetworkPolicyManager.class);
6271
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006272 final long token = Binder.clearCallingIdentity();
6273 final int networkPreference;
6274 try {
6275 networkPreference = netPolicyManager.getMultipathPreference(network);
6276 } finally {
6277 Binder.restoreCallingIdentity(token);
6278 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006279 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006280 return networkPreference;
6281 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006282 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6283 }
6284
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006285 @Override
6286 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006287 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006288 }
6289
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006290 private class InternalHandler extends Handler {
6291 public InternalHandler(Looper looper) {
6292 super(looper);
6293 }
6294
6295 @Override
6296 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006297 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006298 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006299 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006300 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006301 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006302 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006303 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006304 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006305 break;
6306 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006307 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006308 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006309 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006310 break;
6311 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006312 case EVENT_REGISTER_NETWORK_PROVIDER: {
6313 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006314 break;
6315 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006316 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6317 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006318 break;
6319 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006320 case EVENT_REGISTER_NETWORK_OFFER: {
6321 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6322 break;
6323 }
6324 case EVENT_UNREGISTER_NETWORK_OFFER: {
6325 final NetworkOfferInfo offer =
6326 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6327 if (null != offer) {
6328 handleUnregisterNetworkOffer(offer);
6329 }
6330 break;
6331 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006332 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006333 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6334 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6335 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006336 break;
6337 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006338 case EVENT_REGISTER_NETWORK_REQUEST:
6339 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006340 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006341 break;
6342 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006343 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6344 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006345 handleRegisterNetworkRequestWithIntent(msg);
6346 break;
6347 }
Erik Kline155a59a2015-11-25 12:49:38 +09006348 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6349 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6350 handleTimedOutNetworkRequest(nri);
6351 break;
6352 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006353 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6354 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6355 break;
6356 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006357 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006358 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6359 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006360 break;
6361 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006362 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006363 Network network = (Network) msg.obj;
6364 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006365 break;
6366 }
lucaslin2240ef62019-03-12 13:08:03 +08006367 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6368 Network network = (Network) msg.obj;
6369 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6370 toBool(msg.arg2));
6371 break;
6372 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006373 case EVENT_SET_AVOID_UNVALIDATED: {
6374 handleSetAvoidUnvalidated((Network) msg.obj);
6375 break;
6376 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006377 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6378 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006379 break;
6380 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006381 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6382 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006383 break;
6384 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006385 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6386 // handler thread.
6387 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006388 mKeepaliveTracker.handleStartKeepalive(msg);
6389 break;
6390 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006391 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006392 final AutomaticOnOffKeepalive ki =
6393 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6394 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006395
chiachangwang676c84e2023-02-14 09:22:05 +00006396 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006397 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006398 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006399 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006400 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6401 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006402 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6403 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006404 }
6405 }
6406
6407 // If the network no longer exists, then the keepalive should have been
6408 // cleaned up already. There is no point trying to resume keepalives.
6409 if (!networkFound) return;
6410
chiachangwang676c84e2023-02-14 09:22:05 +00006411 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006412 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wangac2e8f32024-01-18 12:55:11 +00006413 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006414 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006415 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006416 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006417 }
6418 break;
6419 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006420 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006421 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006422 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6423 (IBinder) msg.obj);
6424 if (ki == null) {
6425 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006426 return;
6427 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006428 final int reason = msg.arg2;
6429 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006430 break;
6431 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006432 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6433 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6434 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006435 break;
6436 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006437 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6438 handlePrivateDnsSettingsChanged();
6439 break;
dalyk1720e542018-03-05 12:42:22 -05006440 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6441 handlePrivateDnsValidationUpdate(
6442 (PrivateDnsValidationUpdate) msg.obj);
6443 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006444 case EVENT_UID_BLOCKED_REASON_CHANGED:
6445 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006446 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006447 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6448 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6449 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006450 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006451 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6452 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006453 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006454 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006455 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006456 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006457 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6458 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006459 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006460 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006461 }
lucaslin1193a5d2021-01-21 02:04:15 +08006462 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006463 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006464 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006465 break;
paulhu51f77dc2021-06-07 02:34:20 +00006466 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6467 handleMobileDataPreferredUidsChanged();
6468 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006469 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6470 final long timeMs = ((Long) msg.obj).longValue();
6471 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6472 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006473 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6474 handleIngressRateLimitChanged();
6475 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006476 case EVENT_USER_DOES_NOT_WANT:
6477 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6478 if (nai == null) break;
6479 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006480 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006481 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006482 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6483 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6484 break;
chiachangwange0192a72023-02-06 13:25:01 +00006485 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6486 final long time = ((Long) msg.obj).longValue();
6487 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6488 break;
6489 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006490 case EVENT_UID_FROZEN_STATE_CHANGED:
6491 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6492 handleFrozenUids(args.mUids, args.mFrozenStates);
6493 break;
Ying Xu7cabd322024-01-15 18:40:15 -08006494 case EVENT_UID_CARRIER_PRIVILEGES_LOST:
6495 handleUidCarrierPrivilegesLost(msg.arg1);
6496 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006497 }
6498 }
6499 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006500
Lorenzo Colittid6459092016-07-04 12:55:44 +09006501 @Override
markchien5776f962019-12-16 20:15:20 +08006502 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006503 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006504 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006505 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6506 Context.TETHERING_SERVICE);
6507 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006508 }
6509
Lorenzo Colittid6459092016-07-04 12:55:44 +09006510 @Override
markchien5776f962019-12-16 20:15:20 +08006511 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006512 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006513 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006514 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6515 Context.TETHERING_SERVICE);
6516 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006517 }
6518
Lorenzo Colittid6459092016-07-04 12:55:44 +09006519 @Override
markchien5776f962019-12-16 20:15:20 +08006520 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006521 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006522 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006523 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6524 Context.TETHERING_SERVICE);
6525 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006526 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006527
markchien5776f962019-12-16 20:15:20 +08006528
Lorenzo Colittid6459092016-07-04 12:55:44 +09006529 @Override
markchien5776f962019-12-16 20:15:20 +08006530 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006531 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006532 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006533 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6534 Context.TETHERING_SERVICE);
6535
6536 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006537 }
6538
Lorenzo Colittid6459092016-07-04 12:55:44 +09006539 @Override
markchien5776f962019-12-16 20:15:20 +08006540 @Deprecated
6541 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006542 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006543 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6544 Context.TETHERING_SERVICE);
6545
6546 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006547 }
6548
Udam Saini8f7d6a72017-06-07 12:06:28 -07006549 @Override
markchien5776f962019-12-16 20:15:20 +08006550 @Deprecated
6551 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006552 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006553 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6554 Context.TETHERING_SERVICE);
6555 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006556 }
6557
Robert Greenwalte0b00512014-07-02 09:59:16 -07006558 // Called when we lose the default network and have no replacement yet.
6559 // This will automatically be cleared after X seconds or a new default network
6560 // becomes CONNECTED, whichever happens first. The timer is started by the
6561 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006562 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006563 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006564 if (mNetTransitionWakeLock.isHeld()) {
6565 return;
6566 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006567 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006568 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6569 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006570 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006571 mWakelockLogs.log("ACQUIRE for " + forWhom);
6572 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006573 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006574 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006575 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006576 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006577
Hugo Benichi471b62a2017-03-30 23:18:10 +09006578 // Called when we gain a new default network to release the network transition wakelock in a
6579 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6580 // message is cancelled.
6581 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006582 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006583 if (!mNetTransitionWakeLock.isHeld()) {
6584 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006585 }
6586 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006587 // Cancel self timeout on wakelock hold.
6588 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6589 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6590 mHandler.sendMessageDelayed(msg, 1000);
6591 }
6592
6593 // Called when either message of ensureNetworkTransitionWakelock or
6594 // scheduleReleaseNetworkTransitionWakelock is processed.
6595 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6596 String event = eventName(eventId);
6597 synchronized (this) {
6598 if (!mNetTransitionWakeLock.isHeld()) {
6599 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006600 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006601 return;
6602 }
6603 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006604 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6605 mTotalWakelockDurationMs += lockDuration;
6606 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6607 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006608 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006609 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006610 }
6611
Robert Greenwalt986c7412010-09-08 15:24:47 -07006612 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006613 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006614 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006615 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006616 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006617 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006618 }
6619
Lorenzo Colittid6459092016-07-04 12:55:44 +09006620 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006621 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006622 enforceAccessPermission();
6623 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006624 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006625 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006626
6627 final NetworkAgentInfo nai;
6628 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006629 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006630 } else {
6631 nai = getNetworkAgentInfoForNetwork(network);
6632 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006633
6634 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006635 mHandler.obtainMessage(
6636 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006637 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006638
Hugo Benichid6b510a2017-04-06 17:22:18 +09006639 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006640 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006641 if (nai == null
6642 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006643 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006644 return;
6645 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006646 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006647 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006648 mConnectivityDiagnosticsHandler.sendMessage(
6649 mConnectivityDiagnosticsHandler.obtainMessage(
6650 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6651 new ReportedNetworkConnectivityInfo(
6652 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006653 return;
6654 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006655 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006656 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006657 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006658 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006659 // Validating a network that has not yet connected could result in a call to
6660 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006661 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006662 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006663 }
paulhu7aeba372020-12-30 00:42:19 +08006664 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6665 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006666 return;
6667 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006668
6669 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6670 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6671 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6672 // completed.
6673 mConnectivityDiagnosticsHandler.sendMessage(
6674 mConnectivityDiagnosticsHandler.obtainMessage(
6675 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6676 new ReportedNetworkConnectivityInfo(
6677 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006678 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006679 }
6680
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006681 // TODO: call into netd.
6682 private boolean queryUserAccess(int uid, Network network) {
6683 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6684 if (nai == null) return false;
6685
6686 // Any UID can use its default network.
6687 if (nai == getDefaultNetworkForUid(uid)) return true;
6688
6689 // Privileged apps can use any network.
6690 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6691 return true;
6692 }
6693
6694 // An unprivileged UID can use a VPN iff the VPN applies to it.
6695 if (nai.isVPN()) {
6696 return nai.networkCapabilities.appliesToUid(uid);
6697 }
6698
6699 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6700 // sockets, i.e., if it is the owner.
6701 final NetworkAgentInfo vpn = getVpnForUid(uid);
6702 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6703 && uid != vpn.networkCapabilities.getOwnerUid()) {
6704 return false;
6705 }
6706
6707 // The UID's permission must be at least sufficient for the network. Since the restricted
6708 // permission was already checked above, that just leaves background networks.
6709 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6710 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6711 }
6712
6713 // Unrestricted network. Anyone gets to use it.
6714 return true;
6715 }
6716
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006717 /**
6718 * Returns information about the proxy a certain network is using. If given a null network, it
6719 * it will return the proxy for the bound network for the caller app or the default proxy if
6720 * none.
6721 *
6722 * @param network the network we want to get the proxy information for.
6723 * @return Proxy information if a network has a proxy configured, or otherwise null.
6724 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006725 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006726 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006727 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006728 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006729 if (network == null) {
6730 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006731 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006732 true);
6733 if (activeNetwork == null) {
6734 return null;
6735 }
6736 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006737 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006738 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6739 // caller may not have.
6740 return getLinkPropertiesProxyInfo(network);
6741 }
6742 // No proxy info available if the calling UID does not have network access.
6743 return null;
6744 }
6745
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006746
6747 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006748 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6749 if (nai == null) return null;
6750 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006751 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6752 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006753 }
6754 }
6755
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006756 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006757 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006758 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006759 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006760 }
6761
Chalard Jean777e2e52018-06-07 18:02:37 +09006762 @Override
6763 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006764 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006765 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006766 }
6767
Aaron Huang9fe47be2021-06-08 13:11:45 +08006768 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006769 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006770 final NetworkAgentInfo nai = getDefaultNetwork();
6771 // TODO : this method should check that net == nai.network, unfortunately at this point
6772 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6773 // is only ever installed on the default network so in practice this is okay.
6774 if (null == nai) return;
6775 // PAC proxies only work on the default network. Therefore, only the default network
6776 // should have its link properties fixed up for PAC proxies.
6777 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6778 if (nai.everConnected()) {
6779 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6780 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006781 }
6782
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006783 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6784 // when any network changes proxy.
6785 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6786 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006787 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6788 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006789 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6790
Chalard Jean7d97afc2018-06-07 17:41:29 +09006791 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006792 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006793 }
6794 }
6795
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006796 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006797 final private HashMap<Uri, Integer> mUriEventMap;
6798 final private Context mContext;
6799 final private Handler mHandler;
6800
6801 SettingsObserver(Context context, Handler handler) {
6802 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006803 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006804 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006805 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006806 }
6807
Erik Kline05f2b402015-04-30 12:58:40 +09006808 void observe(Uri uri, int what) {
6809 mUriEventMap.put(uri, what);
6810 final ContentResolver resolver = mContext.getContentResolver();
6811 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006812 }
6813
6814 @Override
6815 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006816 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006817 }
6818
6819 @Override
6820 public void onChange(boolean selfChange, Uri uri) {
6821 final Integer what = mUriEventMap.get(uri);
6822 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006823 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006824 } else {
6825 loge("No matching event to send for URI=" + uri);
6826 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006827 }
6828 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006829
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006830 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006831 Log.d(TAG, s);
6832 }
6833
6834 private static void logw(String s) {
6835 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006836 }
6837
Daniel Brightf9e945b2020-06-15 16:10:01 -07006838 private static void logwtf(String s) {
6839 Log.wtf(TAG, s);
6840 }
6841
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006842 private static void logwtf(String s, Throwable t) {
6843 Log.wtf(TAG, s, t);
6844 }
6845
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006846 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006847 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006848 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006849
Hugo Benichi39621362017-02-11 17:04:43 +09006850 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006851 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006852 }
6853
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006854 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006855 * Return the information of all ongoing VPNs.
6856 *
6857 * <p>This method is used to update NetworkStatsService.
6858 *
6859 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006860 */
junyulai2050bed2021-01-23 09:46:34 +08006861 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006862 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006863 if (mLockdownEnabled) {
6864 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006865 }
junyulai2050bed2021-01-23 09:46:34 +08006866 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006867 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006868 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006869 if (info != null) {
6870 infoList.add(info);
6871 }
6872 }
junyulai2050bed2021-01-23 09:46:34 +08006873 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006874 }
6875
6876 /**
6877 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006878 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006879 */
junyulai2050bed2021-01-23 09:46:34 +08006880 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006881 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006882 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6883 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006884 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6885 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6886 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006887 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6888 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006889 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006890 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006891 }
6892 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006893
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006894 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006895
6896 List<String> interfaces = new ArrayList<>();
6897 for (Network network : underlyingNetworks) {
6898 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6899 if (underlyingNai == null) continue;
6900 LinkProperties lp = underlyingNai.linkProperties;
6901 for (String iface : lp.getAllInterfaceNames()) {
6902 if (!TextUtils.isEmpty(iface)) {
6903 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006904 }
6905 }
Benedict Wong34857f82019-06-12 17:46:15 +00006906 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006907
6908 if (interfaces.isEmpty()) return null;
6909
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006910 // Must be non-null or NetworkStatsService will crash.
6911 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6912 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006913 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006914 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006915
junyulai2050bed2021-01-23 09:46:34 +08006916 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6917 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006918 }
6919
James Mattisd31bdfa2020-12-23 16:37:26 -08006920 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006921 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6922 Network[] underlyingNetworks) {
6923 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006924 if (underlyingNetworks == null && defaultNetwork != null) {
6925 // null underlying networks means to track the default.
6926 underlyingNetworks = new Network[] { defaultNetwork };
6927 }
6928 return underlyingNetworks;
6929 }
6930
6931 // Returns true iff |network| is an underlying network of |nai|.
6932 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6933 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6934 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006935 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006936 final Network[] underlying = underlyingNetworksOrDefault(
6937 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006938 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006939 }
6940
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006941 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006942 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006943 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006944 * When underlying networks change, such networks may have to update capabilities to reflect
6945 * things like the metered bit, their transports, and so on. The capabilities are calculated
6946 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006947 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006948 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006949 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006950 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006951 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006952 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006953 }
6954 }
6955 }
6956
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006957 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6958 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6959 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6960 // a VPN is not up.
6961 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6962 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6963 for (UidRange range : blockedUidRanges) {
6964 if (range.contains(uid)) return true;
6965 }
6966 return false;
6967 }
6968
6969 @Override
6970 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006971 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006972 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6973 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6974 }
6975
6976 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6977 if (DBG) {
6978 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6979 + Arrays.toString(ranges));
6980 }
6981 // Cannot use a Set since the list of UID ranges might contain duplicates.
6982 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6983 for (int i = 0; i < ranges.length; i++) {
6984 if (requireVpn) {
6985 newVpnBlockedUidRanges.add(ranges[i]);
6986 } else {
6987 newVpnBlockedUidRanges.remove(ranges[i]);
6988 }
6989 }
6990
6991 try {
6992 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6993 } catch (RemoteException | ServiceSpecificException e) {
6994 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6995 + Arrays.toString(ranges) + "): netd command failed: " + e);
6996 }
6997
Chalard Jeandf29a852023-05-29 17:02:43 +09006998 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006999 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
7000 }
7001
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007002 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
7003 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00007004 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
7005 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007006 }
7007
7008 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
7009 }
7010
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07007011 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007012 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08007013 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007014 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01007015 }
7016
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007017 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
7018 return mLockdownEnabled
7019 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
7020 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00007021 }
7022
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007023 private NetworkAgentInfo getLegacyLockdownNai() {
7024 if (!mLockdownEnabled) {
7025 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00007026 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007027 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007028 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
7029 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00007030
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007031 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007032 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
7033 // a local variable. There is no need to make a copy because its contents cannot change.
7034 final Network[] underlying = nai.declaredUnderlyingNetworks;
7035 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007036 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007037 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007038
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007039 // The legacy lockdown VPN always uses the default network.
7040 // If the VPN's underlying network is no longer the current default network, it means that
7041 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007042 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
7043 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007044 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007045 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007046 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007047 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007048
7049 return nai;
7050 };
7051
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007052 // TODO: move all callers to filterForLegacyLockdown and delete this method.
7053 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
7054 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007055 private DetailedState getLegacyLockdownState(DetailedState origState) {
7056 if (origState != DetailedState.CONNECTED) {
7057 return origState;
7058 }
7059 return (mLockdownEnabled && getLegacyLockdownNai() == null)
7060 ? DetailedState.CONNECTING
7061 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007062 }
7063
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007064 private void filterForLegacyLockdown(NetworkInfo ni) {
7065 if (!mLockdownEnabled || !ni.isConnected()) return;
7066 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
7067 // state of its VPN. This is to ensure that when an underlying network connects, apps will
7068 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
7069 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
7070 // network, this time with a state of CONNECTED.
7071 //
7072 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
7073 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
7074 // is not too far off the truth, since an always-on VPN, when not connected, is always
7075 // trying to reconnect.
7076 if (getLegacyLockdownNai() == null) {
7077 ni.setDetailedState(DetailedState.CONNECTING, "", null);
7078 }
7079 }
7080
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007081 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07007082 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04007083 String action) {
paulhu8e96a752019-08-12 16:25:11 +08007084 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09007085 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
7086 return;
7087 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04007088 final long ident = Binder.clearCallingIdentity();
7089 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09007090 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007091 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09007092 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04007093 } finally {
7094 Binder.restoreCallingIdentity(ident);
7095 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07007096 }
Wink Savillecb117d32013-08-29 14:57:08 -07007097
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007098 @Override
7099 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01007100 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007101 final long ident = Binder.clearCallingIdentity();
7102 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007103 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09007104 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007105 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
7106 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08007107 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007108 } finally {
7109 Binder.restoreCallingIdentity(ident);
7110 }
7111 }
7112
James Mattis02220e22021-03-13 19:27:21 -08007113 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08007114 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7115 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7116 }
Chalard Jeane0abd522023-01-23 16:47:43 +09007117 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007118 }
7119
James Mattis02220e22021-03-13 19:27:21 -08007120 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09007121 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007122 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08007123 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
7124 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09007125 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08007126 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7127 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7128 }
junyulaid91e7052020-08-28 13:44:33 +08007129 }
7130
James Mattis02220e22021-03-13 19:27:21 -08007131 private void onPackageChanged(@NonNull final String packageName) {
7132 // This is necessary in case a package is added or removed, but also when it's replaced to
7133 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
7134 // as one in the preferences, then it should follow the same routing as that other package,
7135 // which means updating the rules is never to be needed in this case (whether it joins or
7136 // leaves a UID with a preference).
7137 if (isMappedInOemNetworkPreference(packageName)) {
7138 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7139 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007140
7141 // Invalidates cache entry when the package is updated.
7142 synchronized (mSelfCertifiedCapabilityCache) {
7143 mSelfCertifiedCapabilityCache.remove(packageName);
7144 }
James Mattis02220e22021-03-13 19:27:21 -08007145 }
7146
7147 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007148 @Override
7149 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007150 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007151 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007152 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007153
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007154 // User should be filled for below intents, check the existence.
7155 if (user == null) {
7156 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7157 return;
7158 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007159
Lorenzo Colitticd675292021-02-04 17:32:07 +09007160 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007161 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007162 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007163 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007164 } else {
junyulaid91e7052020-08-28 13:44:33 +08007165 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007166 }
7167 }
7168 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007169
James Mattis02220e22021-03-13 19:27:21 -08007170 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7171 @Override
7172 public void onReceive(Context context, Intent intent) {
7173 ensureRunningOnConnectivityServiceThread();
7174 switch (intent.getAction()) {
7175 case Intent.ACTION_PACKAGE_ADDED:
7176 case Intent.ACTION_PACKAGE_REMOVED:
7177 case Intent.ACTION_PACKAGE_REPLACED:
7178 onPackageChanged(intent.getData().getSchemeSpecificPart());
7179 break;
7180 default:
7181 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7182 }
7183 }
7184 };
7185
Junyu Lai38c75032023-12-04 07:52:19 +00007186 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
7187 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
7188 @Override
7189 public void onReceive(Context context, Intent intent) {
7190 if (mDeps.isAtLeastV()) {
7191 throw new IllegalStateException(
7192 "data saver status should be updated from platform");
7193 }
7194 ensureRunningOnConnectivityServiceThread();
7195 switch (intent.getAction()) {
7196 case ACTION_RESTRICT_BACKGROUND_CHANGED:
7197 // If the uid is present in the deny list, the API will consistently
7198 // return ENABLED. To retrieve the global switch status, the system
7199 // uid is chosen because it will never be included in the deny list.
7200 final int dataSaverForSystemUid =
7201 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
7202 final boolean isDataSaverEnabled = (dataSaverForSystemUid
7203 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
7204 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
7205 break;
7206 default:
7207 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7208 }
7209 }
7210 };
7211
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007212 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007213 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007214
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007215 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007216 public final String name;
7217 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007218 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007219 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007220
lifraf3a3492021-03-10 13:58:14 +08007221 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7222 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007223 this.name = name;
7224 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007225 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007226 mDeathRecipient = deathRecipient;
7227
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007228 if (mDeathRecipient == null) {
7229 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007230 }
7231 }
7232
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007233 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007234 try {
7235 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7236 } catch (RemoteException e) {
7237 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007238 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007239 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007240 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007241
James Mattis4fce5d12020-11-12 15:53:42 -08007242 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7243 for (int i = 0; i < requests.size(); i++) {
7244 ensureNetworkRequestHasType(requests.get(i));
7245 }
7246 }
7247
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007248 private void ensureNetworkRequestHasType(NetworkRequest request) {
7249 if (request.type == NetworkRequest.Type.NONE) {
7250 throw new IllegalArgumentException(
7251 "All NetworkRequests in ConnectivityService must have a type");
7252 }
7253 }
7254
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007255 /**
7256 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007257 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007258 */
James Mattis258ea3c2020-11-15 15:04:40 -08007259 @VisibleForTesting
7260 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007261 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7262 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007263 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007264
James Mattisa076c532020-12-02 14:12:41 -08007265 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7266 void setSatisfier(
7267 @Nullable final NetworkAgentInfo satisfier,
7268 @Nullable final NetworkRequest activeRequest) {
7269 mSatisfier = satisfier;
7270 mActiveRequest = activeRequest;
7271 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007272
James Mattisd31bdfa2020-12-23 16:37:26 -08007273 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007274 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007275 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007276 private NetworkAgentInfo mSatisfier;
7277 NetworkAgentInfo getSatisfier() {
7278 return mSatisfier;
7279 }
7280
7281 // The request in mRequests assigned to a network agent. This is null if none of the
7282 // requests in mRequests can be satisfied. This member has the constraint of only being
7283 // accessible on the handler thread.
7284 @Nullable
7285 private NetworkRequest mActiveRequest;
7286 NetworkRequest getActiveRequest() {
7287 return mActiveRequest;
7288 }
7289
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007290 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007291 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007292 @Nullable
7293 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007294
7295 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007296 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007297 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007298 final int mPid;
7299 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007300 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007301 @Nullable
7302 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007303
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007304 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007305 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007306
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007307 // Effective UID of this request. This is different from mUid when a privileged process
7308 // files a request on behalf of another UID. This UID is used to determine blocked status,
7309 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7310 // maximum limit of registered callbacks per UID.
7311 final int mAsUid;
7312
paulhu48291862021-07-14 14:53:57 +08007313 // Preference order of this request.
7314 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007315
James Mattis3ce3d3c2021-02-09 18:18:28 -08007316 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7317 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7318 // maintained for keying off of. This is only a concern when the original nri
7319 // mNetworkRequests changes which happens currently for apps that register callbacks to
7320 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7321 // that match the per-app default nri that currently tracks the calling app's uid so that
7322 // callbacks are fired at the appropriate time. When the callbacks fire,
7323 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7324 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7325 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7326 @NonNull
7327 private final NetworkRequest mNetworkRequestForCallback;
7328 NetworkRequest getNetworkRequestForCallback() {
7329 return mNetworkRequestForCallback;
7330 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007331
James Mattisd31bdfa2020-12-23 16:37:26 -08007332 /**
7333 * Get the list of UIDs this nri applies to.
7334 */
7335 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007336 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007337 // networkCapabilities.getUids() returns a defensive copy.
7338 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007339 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7340 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007341 }
7342
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007343 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7344 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007345 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007346 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007347 }
7348
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007349 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007350 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007351 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007352 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007353 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007354 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007355 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007356 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007357 mBinder = null;
7358 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007359 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007360 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007361 mPerUidCounter = getRequestCounter(this);
7362 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007363 /**
7364 * Location sensitive data not included in pending intent. Only included in
7365 * {@link NetworkCallback}.
7366 */
7367 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007368 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007369 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007370 }
7371
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007372 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007373 @Nullable final IBinder binder,
7374 @NetworkCallback.Flag int callbackFlags,
7375 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007376 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7377 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007378 }
7379
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007380 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007381 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007382 @Nullable final IBinder binder,
7383 @NetworkCallback.Flag int callbackFlags,
7384 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007385 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007386 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007387 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007388 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007389 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007390 mBinder = binder;
7391 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007392 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007393 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007394 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007395 mPerUidCounter = getRequestCounter(this);
7396 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007397 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007398 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007399 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007400 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007401 }
7402
James Mattis3ce3d3c2021-02-09 18:18:28 -08007403 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7404 @NonNull final List<NetworkRequest> r) {
7405 super();
7406 ensureAllNetworkRequestsHaveType(r);
7407 mRequests = initializeRequests(r);
7408 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007409 final NetworkAgentInfo satisfier = nri.getSatisfier();
7410 if (null != satisfier) {
7411 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7412 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007413 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007414 // As this code creates a new NRI with a new set of requests, figure out which of
7415 // the list of requests should be the active request. It is always the first
7416 // request of the list that can be satisfied by the satisfier since the order of
7417 // requests is a priority order.
7418 // Note even in the presence of a satisfier there may not be an active request,
7419 // when the satisfier is the no-service network.
7420 NetworkRequest activeRequest = null;
7421 for (final NetworkRequest candidate : r) {
7422 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7423 activeRequest = candidate;
7424 break;
7425 }
7426 }
7427 setSatisfier(satisfier, activeRequest);
7428 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007429 mMessenger = nri.mMessenger;
7430 mBinder = nri.mBinder;
7431 mPid = nri.mPid;
7432 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007433 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007434 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007435 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007436 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007437 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007438 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007439 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007440 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007441 }
7442
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007443 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007444 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007445 }
7446
paulhue9913722021-05-26 15:19:20 +08007447 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007448 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007449 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007450 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007451 }
7452
James Mattis2516da32021-01-31 17:06:19 -08007453 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7454 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7455 // false.
7456 boolean isBeingSatisfied() {
7457 return (null != mSatisfier && null != mActiveRequest);
7458 }
7459
James Mattis3d229892020-11-16 16:46:28 -08007460 boolean isMultilayerRequest() {
7461 return mRequests.size() > 1;
7462 }
7463
James Mattis45d81842021-01-10 14:24:24 -08007464 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7465 // Creating a defensive copy to prevent the sender from modifying the list being
7466 // reflected in the return value of this method.
7467 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007468 return Collections.unmodifiableList(tempRequests);
7469 }
7470
James Mattisb1392002021-03-31 13:57:52 -07007471 void linkDeathRecipient() {
7472 if (null != mBinder) {
7473 try {
7474 mBinder.linkToDeath(this, 0);
7475 } catch (RemoteException e) {
7476 binderDied();
7477 }
7478 }
7479 }
7480
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007481 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007482 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007483 try {
7484 mBinder.unlinkToDeath(this, 0);
7485 } catch (NoSuchElementException e) {
7486 // Temporary workaround for b/194394697 pending analysis of additional logs
7487 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7488 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007489 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007490 }
7491
paulhu48291862021-07-14 14:53:57 +08007492 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7493 // Compare two preference orders.
7494 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007495 }
7496
paulhu48291862021-07-14 14:53:57 +08007497 int getPreferenceOrderForNetd() {
7498 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7499 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7500 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007501 }
paulhu48291862021-07-14 14:53:57 +08007502 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007503 }
7504
James Mattis4fce5d12020-11-12 15:53:42 -08007505 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007506 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007507 // As an immutable collection, mRequests cannot change by the time the
7508 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7509 // is acceptable. Use handleReleaseNetworkRequest and not directly
7510 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7511 // the app already unregistered the request.
7512 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7513 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007514 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007515
James Mattis4fce5d12020-11-12 15:53:42 -08007516 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007517 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007518 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7519 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007520 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007521 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007522 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007523 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007524 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007525 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007526 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007527 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007528 }
7529
Junyu Lai00d92df2022-07-05 11:01:52 +08007530 // Keep backward compatibility since the ServiceSpecificException is used by
7531 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7532 public static class RequestInfoPerUidCounter extends PerUidCounter {
7533 RequestInfoPerUidCounter(int maxCountPerUid) {
7534 super(maxCountPerUid);
7535 }
7536
7537 @Override
7538 public synchronized void incrementCountOrThrow(int uid) {
7539 try {
7540 super.incrementCountOrThrow(uid);
7541 } catch (IllegalStateException e) {
7542 throw new ServiceSpecificException(
7543 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7544 "Uid " + uid + " exceeded its allotted requests limit");
7545 }
7546 }
7547
7548 @Override
7549 public synchronized void decrementCountOrThrow(int uid) {
7550 throw new UnsupportedOperationException("Use decrementCount instead.");
7551 }
7552
7553 public synchronized void decrementCount(int uid) {
7554 try {
7555 super.decrementCountOrThrow(uid);
7556 } catch (IllegalStateException e) {
7557 logwtf("Exception when decrement per uid request count: ", e);
7558 }
7559 }
7560 }
7561
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007562 // This checks that the passed capabilities either do not request a
7563 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007564 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007565 int callerPid, int callerUid, String callerPackageName) {
Junyu Lai71b51532024-02-01 10:39:01 +08007566 if (null != nc.getSsid() && !hasSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007567 throw new SecurityException("Insufficient permissions to request a specific SSID");
7568 }
paulhu1a407652019-03-22 16:35:06 +08007569
7570 if (nc.hasSignalStrength()
Junyu Lai71b51532024-02-01 10:39:01 +08007571 && !hasNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
paulhu1a407652019-03-22 16:35:06 +08007572 throw new SecurityException(
7573 "Insufficient permissions to request a specific signal strength");
7574 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007575 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007576
Ying Xu7cabd322024-01-15 18:40:15 -08007577 if (nc.getSubscriptionIds().isEmpty()) {
7578 return;
Benedict Wong53de25f2021-03-24 14:01:51 -07007579 }
Ying Xu7cabd322024-01-15 18:40:15 -08007580 if (mRequestRestrictedWifiEnabled
7581 && canRequestRestrictedNetworkDueToCarrierPrivileges(nc, callerUid)) {
7582 return;
7583 }
7584 enforceNetworkFactoryPermission();
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007585 }
7586
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007587 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007588 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007589 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007590 // mNetworkRequests may contain the same value multiple times in case of
7591 // multilayer requests. It won't matter in this case because the thresholds
7592 // will then be the same and be deduplicated as they enter the `thresholds` set.
7593 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007594 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7595 for (final NetworkRequest req : nri.mRequests) {
7596 if (req.networkCapabilities.hasSignalStrength()
7597 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7598 thresholds.add(req.networkCapabilities.getSignalStrength());
7599 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007600 }
7601 }
7602 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007603 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007604 }
7605
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007606 private void updateSignalStrengthThresholds(
7607 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007608 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007609
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007610 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007611 String detail;
7612 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7613 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7614 } else {
7615 detail = reason;
7616 }
7617 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007618 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007619 }
7620
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007621 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007622 }
7623
Chalard Jeandd421992021-12-16 23:16:02 +09007624 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007625 if (nc == null) {
7626 return;
7627 }
7628 NetworkSpecifier ns = nc.getNetworkSpecifier();
7629 if (ns == null) {
7630 return;
7631 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007632 if (ns instanceof MatchAllNetworkSpecifier) {
7633 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7634 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007635 }
7636
Chalard Jeandd421992021-12-16 23:16:02 +09007637 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007638 ensureValidNetworkSpecifier(nc);
7639 if (nc.isPrivateDnsBroken()) {
7640 throw new IllegalArgumentException("Can't request broken private DNS");
7641 }
Chalard Jeande665262022-02-25 16:12:12 +09007642 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007643 throw new IllegalArgumentException("Can't request access UIDs");
7644 }
lucasline117e2e2019-10-22 18:27:33 +08007645 }
7646
Chalard Jeandd421992021-12-16 23:16:02 +09007647 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7648 ensureListenableCapabilities(nc);
7649 final String badCapability = nc.describeFirstNonRequestableCapability();
7650 if (badCapability != null) {
7651 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7652 }
7653 }
7654
Chiachang Wang3bc52762021-11-25 14:17:57 +08007655 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7656 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007657 private boolean isTargetSdkAtleast(int version, int callingUid,
7658 @NonNull String callingPackageName) {
7659 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007660 final PackageManager pm =
7661 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007662 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007663 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007664 if (callingVersion < version) return false;
7665 } catch (PackageManager.NameNotFoundException e) { }
7666 return true;
7667 }
7668
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007669 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007670 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007671 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007672 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007673 @Nullable String callingAttributionTag) {
Junyu Lai71b51532024-02-01 10:39:01 +08007674 if (legacyType != TYPE_NONE && !hasNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007675 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7676 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007677 throw new SecurityException("Insufficient permissions to specify legacy type");
7678 }
markchienfac84a22020-03-18 21:16:15 +08007679 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007680 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007681 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007682 // Privileged callers can track the default network of another UID by passing in a UID.
7683 if (asUid != Process.INVALID_UID) {
7684 enforceSettingsPermission();
7685 } else {
7686 asUid = callingUid;
7687 }
junyulaiad010792021-01-11 16:53:38 +08007688 final NetworkRequest.Type reqType;
7689 try {
7690 reqType = NetworkRequest.Type.values()[reqTypeInt];
7691 } catch (ArrayIndexOutOfBoundsException e) {
7692 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7693 }
7694 switch (reqType) {
7695 case TRACK_DEFAULT:
7696 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007697 // is unused and will be replaced by ones appropriate for the UID (usually, the
7698 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007699 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007700 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007701 enforceAccessPermission();
7702 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007703 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007704 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007705 networkCapabilities = new NetworkCapabilities(defaultNc);
7706 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007707 case BACKGROUND_REQUEST:
7708 enforceNetworkStackOrSettingsPermission();
7709 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007710 case REQUEST:
7711 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7712 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007713 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007714 // TODO: this is incorrect. We mark the request as metered or not depending on
7715 // the state of the app when the request is filed, but we never change the
7716 // request if the app changes network state. http://b/29964605
7717 enforceMeteredApnPolicy(networkCapabilities);
7718 break;
junyulai1b1c8742021-03-12 20:05:08 +08007719 case LISTEN_FOR_BEST:
7720 enforceAccessPermission();
7721 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7722 break;
junyulaiad010792021-01-11 16:53:38 +08007723 default:
7724 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007725 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007726 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007727 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007728 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007729
junyulai1b1c8742021-03-12 20:05:08 +08007730 // Enforce FOREGROUND if the caller does not have permission to use background network.
7731 if (reqType == LISTEN_FOR_BEST) {
7732 restrictBackgroundRequestForCaller(networkCapabilities);
7733 }
7734
7735 // Set the UID range for this request to the single UID of the requester, unless the
7736 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007737 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7738 // are no visible methods to set the UIDs, an app could use reflection to try and get
7739 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007740 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007741 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7742 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007743
Etan Cohen85000162017-02-05 10:42:27 -08007744 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007745 throw new IllegalArgumentException("Bad timeout specified");
7746 }
Etan Cohen9786d922015-11-18 10:56:15 -08007747
James Mattis3ce3d3c2021-02-09 18:18:28 -08007748 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007749 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007750 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007751 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007752 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007753 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007754
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007755 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7756 // copied from the default request above. (This is necessary to ensure, for example, that
7757 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7758 // changes don't alter request matching.
7759 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7760 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007761 throw new IllegalStateException(
7762 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007763 + networkCapabilities + " vs. " + defaultNc);
7764 }
7765
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007766 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007767 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007768 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007769 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007770 }
7771 return networkRequest;
7772 }
7773
James Mattis3ce3d3c2021-02-09 18:18:28 -08007774 /**
7775 * Return the nri to be used when registering a network request. Specifically, this is used with
7776 * requests registered to track the default request. If there is currently a per-app default
7777 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7778 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007779 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7780 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007781 * @param nr the network request for the nri.
7782 * @param msgr the messenger for the nri.
7783 * @param binder the binder for the nri.
7784 * @param callingAttributionTag the calling attribution tag for the nri.
7785 * @return the nri to register.
7786 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007787 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007788 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007789 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007790 @Nullable String callingAttributionTag) {
7791 final List<NetworkRequest> requests;
7792 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7793 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007794 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007795 } else {
7796 requests = Collections.singletonList(nr);
7797 }
Roshan Pius951c0032020-12-22 15:10:42 -08007798 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007799 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007800 }
7801
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007802 private boolean shouldCheckCapabilitiesDeclaration(
7803 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7804 @NonNull final String callingPackageName) {
7805 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7806 // Only run the check if the change is enabled.
7807 if (!mDeps.isChangeEnabled(
7808 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7809 callingPackageName, user)) {
7810 return false;
7811 }
7812
7813 return networkCapabilities.hasCapability(
7814 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7815 || networkCapabilities.hasCapability(
7816 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7817 }
7818
7819 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007820 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007821 // This check is added to fix the linter error for "current min is 30", which is not going
7822 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007823 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007824 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7825 return;
7826 }
7827 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007828 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007829 try {
7830 synchronized (mSelfCertifiedCapabilityCache) {
7831 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7832 callerPackageName);
7833 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007834 final PackageManager packageManager =
7835 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
7836 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007837 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7838 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7839 callerPackageName
7840 );
7841 final XmlResourceParser parser = packageManager
7842 .getResourcesForApplication(callerPackageName)
7843 .getXml(networkSliceProperty.getResourceId());
7844 applicationNetworkCapabilities =
7845 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7846 mSelfCertifiedCapabilityCache.put(callerPackageName,
7847 applicationNetworkCapabilities);
7848 }
7849
7850 }
7851 } catch (PackageManager.NameNotFoundException ne) {
7852 throw new SecurityException(
7853 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7854 + " property");
7855 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7856 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007857 } finally {
7858 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007859 }
7860
7861 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7862 networkCapabilities);
7863 }
Ying Xu7cabd322024-01-15 18:40:15 -08007864
7865 private boolean canRequestRestrictedNetworkDueToCarrierPrivileges(
7866 NetworkCapabilities networkCapabilities, int callingUid) {
7867 if (mRequestRestrictedWifiEnabled) {
7868 // For U+ devices, callers with carrier privilege could request restricted networks
7869 // with CBS capabilities, or any restricted WiFi networks.
7870 return ((networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7871 || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))
7872 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities));
7873 } else {
7874 // For T+ devices, callers with carrier privilege could request with CBS
7875 // capabilities.
7876 return (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7877 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities));
7878 }
7879 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007880 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007881 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007882 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7883 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007884 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
7885 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007886 }
Ying Xu7cabd322024-01-15 18:40:15 -08007887 if (!networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
7888 if (!canRequestRestrictedNetworkDueToCarrierPrivileges(
7889 networkCapabilities, callingUid)) {
7890 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007891 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007892 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007893 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007894 }
7895 }
7896
fenglu3f357402015-03-20 11:29:56 -07007897 @Override
fenglub00f4882015-04-21 17:12:05 -07007898 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007899 enforceAccessPermission();
7900 NetworkAgentInfo nai = null;
7901 if (network == null) {
7902 return false;
7903 }
7904 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007905 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007906 }
7907 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007908 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007909 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007910 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007911 Integer uidReqs = mBandwidthRequests.get(uid);
7912 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007913 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007914 }
7915 mBandwidthRequests.put(uid, ++uidReqs);
7916 }
fenglu3f357402015-03-20 11:29:56 -07007917 return true;
7918 }
7919 return false;
7920 }
7921
Felipe Leme0a5ae422016-06-20 16:36:29 -07007922 private boolean isSystem(int uid) {
7923 return uid < Process.FIRST_APPLICATION_UID;
7924 }
fenglu3f357402015-03-20 11:29:56 -07007925
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007926 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007927 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007928 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007929 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007930 return;
7931 }
Hugo Benichi39621362017-02-11 17:04:43 +09007932 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7933 // Policy already enforced.
7934 return;
7935 }
paulhuaf50d7d2020-12-24 19:47:34 +08007936 final long ident = Binder.clearCallingIdentity();
7937 try {
7938 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7939 // If UID is restricted, don't allow them to bring up metered APNs.
7940 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7941 }
7942 } finally {
7943 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007944 }
7945 }
7946
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007947 @Override
7948 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007949 PendingIntent operation, @NonNull String callingPackageName,
7950 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007951 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007952 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007953 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007954 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007955 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007956 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007957 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007958 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007959 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007960 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7961 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007962
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007963 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007964 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007965 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7966 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007967 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007968 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7969 nri));
7970 return networkRequest;
7971 }
7972
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007973 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7974 mHandler.sendMessageDelayed(
7975 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007976 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007977 }
7978
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007979 @Override
7980 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007981 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007982 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007983 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007984 }
7985
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007986 // In order to implement the compatibility measure for pre-M apps that call
7987 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7988 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7989 // This ensures it has permission to do so.
7990 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7991 if (nc == null) {
7992 return false;
7993 }
7994 int[] transportTypes = nc.getTransportTypes();
7995 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7996 return false;
7997 }
7998 try {
7999 mContext.enforceCallingOrSelfPermission(
8000 android.Manifest.permission.ACCESS_WIFI_STATE,
8001 "ConnectivityService");
8002 } catch (SecurityException e) {
8003 return false;
8004 }
8005 return true;
8006 }
8007
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008008 @Override
8009 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08008010 Messenger messenger, IBinder binder,
8011 @NetworkCallback.Flag int callbackFlags,
8012 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008013 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09008014 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
8015 enforceAccessPermission();
8016 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008017
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008018 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008019 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008020 Binder.getCallingPid(), callingUid, callingPackageName);
8021 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09008022 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
8023 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
8024 // onLost and onAvailable callbacks when networks move in and out of the background.
8025 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
8026 // can't request networks.
8027 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09008028 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07008029
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008030 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09008031 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08008032 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008033 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08008034 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09008035 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008036
8037 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
8038 return networkRequest;
8039 }
8040
8041 @Override
8042 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08008043 PendingIntent operation, @NonNull String callingPackageName,
8044 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00008045 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008046 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04008047 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
8048 enforceAccessPermission();
8049 }
Chalard Jeandd421992021-12-16 23:16:02 +09008050 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008051 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008052 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09008053 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08008054 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09008055
8056 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09008057 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008058 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
8059 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09008060 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04008061
WeiZhang1cc3f172021-06-03 19:02:04 -05008062 mHandler.sendMessage(mHandler.obtainMessage(
8063 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008064 }
8065
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008066 /** Returns the next Network provider ID. */
8067 public final int nextNetworkProviderId() {
8068 return mNextNetworkProviderId.getAndIncrement();
8069 }
8070
Erik Kline0c04b742016-07-07 16:50:58 +09008071 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008072 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09008073 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09008074 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09008075 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008076 }
8077
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008078 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
8079 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008080 // Avoid creating duplicates. even if an app makes a direct AIDL call.
8081 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
8082 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08008083 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008084 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008085 return;
8086 }
8087
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008088 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
8089 mNetworkProviderInfos.put(npi.messenger, npi);
8090 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008091 }
8092
8093 @Override
8094 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008095 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08008096 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008097 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08008098 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008099 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
8100 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008101 }
8102
8103 @Override
8104 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008105 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008106 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008107 }
8108
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008109 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09008110 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008111 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
8112 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09008113 Objects.requireNonNull(score);
8114 Objects.requireNonNull(caps);
8115 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008116 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008117 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09008118 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
8119 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008120 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
8121 }
8122
Chalard Jeanbb902a52021-08-18 01:35:19 +09008123 private void updateOfferScore(final NetworkOffer offer) {
8124 final boolean yieldToBadWiFi =
8125 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
8126 final NetworkOffer newOffer = new NetworkOffer(
8127 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
8128 offer.caps, offer.callback, offer.providerId);
8129 if (offer.equals(newOffer)) return;
8130 handleRegisterNetworkOffer(newOffer);
8131 }
8132
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008133 @Override
8134 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08008135 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008136 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
8137 }
8138
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008139 private void handleUnregisterNetworkProvider(Messenger messenger) {
8140 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
8141 if (npi == null) {
8142 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008143 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008144 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008145 // Unregister all the offers from this provider
8146 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
8147 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09008148 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008149 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
8150 toRemove.add(noi);
8151 }
8152 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09008153 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008154 handleUnregisterNetworkOffer(noi);
8155 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008156 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008157 }
8158
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008159 @Override
James Mattisf7027322020-12-13 16:28:14 -08008160 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008161 if (request.hasTransport(TRANSPORT_TEST)) {
8162 enforceNetworkFactoryOrTestNetworksPermission();
8163 } else {
8164 enforceNetworkFactoryPermission();
8165 }
James Mattisf7027322020-12-13 16:28:14 -08008166 final NetworkRequestInfo nri = mNetworkRequests.get(request);
8167 if (nri != null) {
8168 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
8169 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
8170 mHandler.post(() -> handleReleaseNetworkRequest(
8171 nri.mRequests.get(0), mDeps.getCallingUid(), true));
8172 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008173 }
8174
Paul Jensen1f567382015-02-13 14:18:39 -05008175 // NOTE: Accessed on multiple threads, must be synchronized on itself.
8176 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008177 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008178 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008179 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008180 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008181 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008182
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008183 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008184 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008185 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008186
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008187 // UID ranges for users that are currently blocked by VPNs.
8188 // This array is accessed and iterated on multiple threads without holding locks, so its
8189 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8190 // (on the handler thread).
8191 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8192
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008193 // Must only be accessed on the handler thread
8194 @NonNull
8195 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8196
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008197 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008198 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008199
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008200 // Current OEM network preferences. This object must only be written to on the handler thread.
8201 // Since it is immutable and always non-null, other threads may read it if they only care
8202 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008203 @NonNull
8204 private OemNetworkPreferences mOemNetworkPreferences =
8205 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008206 // Current per-profile network preferences. This object follows the same threading rules as
8207 // the OEM network preferences above.
8208 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008209 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8210 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008211
lucaslin3ba7cc22022-12-19 02:35:33 +00008212 // Current VPN network preferences. This object follows the same threading rules as the OEM
8213 // network preferences above.
8214 @NonNull
8215 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8216 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8217
paulhu51f77dc2021-06-07 02:34:20 +00008218 // A set of UIDs that should use mobile data preferentially if available. This object follows
8219 // the same threading rules as the OEM network preferences above.
8220 @NonNull
8221 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8222
James Mattiscb1e0362021-04-06 17:07:42 -07008223 // OemNetworkPreferences activity String log entries.
8224 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8225 @NonNull
8226 private final LocalLog mOemNetworkPreferencesLogs =
8227 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8228
James Mattis02220e22021-03-13 19:27:21 -08008229 /**
8230 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8231 * @param packageName the package name to check existence of a mapping for.
8232 * @return true if a mapping exists, false otherwise
8233 */
8234 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8235 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8236 }
8237
James Mattise3ef1912020-12-20 11:09:58 -08008238 // The always-on request for an Internet-capable network that apps without a specific default
8239 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008240 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008241 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008242 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008243 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008244 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008245 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008246 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008247
James Mattisd31bdfa2020-12-23 16:37:26 -08008248 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8249 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8250 }
8251
8252 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008253 * Return the default network request currently tracking the given uid.
8254 * @param uid the uid to check.
8255 * @return the NetworkRequestInfo tracking the given uid.
8256 */
8257 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008258 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008259 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008260 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008261 // Checking the first request is sufficient as only multilayer requests will have more
8262 // than one request and for multilayer, all requests will track the same uids.
8263 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008264 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008265 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008266 highestPriorityNri = nri;
8267 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008268 }
8269 }
paulhuaa0743d2021-05-26 21:56:03 +08008270 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008271 }
8272
8273 /**
8274 * Get a copy of the network requests of the default request that is currently tracking the
8275 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008276 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8277 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008278 * @param requestorUid the uid to check the default for.
8279 * @param requestorPackageName the requestor's package name.
8280 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8281 */
8282 @NonNull
8283 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008284 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008285 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008286 getDefaultRequestTrackingUid(asUid).mRequests,
8287 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008288 }
8289
8290 /**
8291 * Copy the given nri's NetworkRequest collection.
8292 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008293 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8294 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008295 * @param requestorUid the uid to set on the copied collection.
8296 * @param requestorPackageName the package name to set on the copied collection.
8297 * @return the copied NetworkRequest collection.
8298 */
8299 @NonNull
8300 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008301 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8302 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008303 final List<NetworkRequest> requests = new ArrayList<>();
8304 for (final NetworkRequest nr : requestsToCopy) {
8305 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008306 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008307 nr.legacyType, nextNetworkRequestId(), nr.type));
8308 }
8309 return requests;
8310 }
8311
8312 @NonNull
8313 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008314 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8315 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008316 // These capabilities are for a TRACK_DEFAULT callback, so:
8317 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8318 // mDefaultRequest and a per-UID default request.
8319 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008320 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008321 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008322 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8323 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008324 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008325 restrictRequestUidsForCallerAndSetRequestorInfo(
8326 netCap, requestorUid, requestorPackageName);
8327 return netCap;
8328 }
8329
8330 /**
8331 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8332 * @param nr the network request to check for equality against.
8333 * @return the nri if one exists, null otherwise.
8334 */
8335 @Nullable
8336 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8337 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8338 if (nri.getNetworkRequestForCallback().equals(nr)) {
8339 return nri;
8340 }
8341 }
8342 return null;
8343 }
8344
8345 /**
8346 * Check if an nri is currently being managed by per-app default networking.
8347 * @param nri the nri to check.
8348 * @return true if this nri is currently being managed by per-app default networking.
8349 */
8350 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8351 // nri.mRequests.get(0) is only different from the original request filed in
8352 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8353 // functionality therefore if these two don't match, it means this particular nri is
8354 // currently being managed by a per-app default.
8355 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8356 }
8357
8358 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008359 * Determine if an nri is a managed default request that disallows default networking.
8360 * @param nri the request to evaluate
8361 * @return true if device-default networking is disallowed
8362 */
8363 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8364 // Check if this nri is a managed default that supports the default network at its
8365 // lowest priority request.
8366 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8367 final NetworkCapabilities lowestPriorityNetCap =
8368 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8369 return isPerAppDefaultRequest(nri)
8370 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8371 lowestPriorityNetCap));
8372 }
8373
Erik Kline05f2b402015-04-30 12:58:40 +09008374 // Request used to optionally keep mobile data active even when higher
8375 // priority networks like Wi-Fi are active.
8376 private final NetworkRequest mDefaultMobileDataRequest;
8377
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008378 // Request used to optionally keep wifi data active even when higher
8379 // priority networks like ethernet are active.
8380 private final NetworkRequest mDefaultWifiRequest;
8381
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008382 // Request used to optionally keep vehicle internal network always active
8383 private final NetworkRequest mDefaultVehicleRequest;
8384
James Mattisd31bdfa2020-12-23 16:37:26 -08008385 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8386 // network with no service. This NAI should never be matched against, nor should any public API
8387 // ever return the associated network. For this reason, this NAI is not in the list of available
8388 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8389 // default requests that don't support using the device default network which will ultimately
8390 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8391 @VisibleForTesting
8392 final NetworkAgentInfo mNoServiceNetwork;
8393
Chalard Jean5b409c72021-02-04 13:12:59 +09008394 // The NetworkAgentInfo currently satisfying the default request, if any.
8395 private NetworkAgentInfo getDefaultNetwork() {
8396 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008397 }
8398
James Mattis2516da32021-01-31 17:06:19 -08008399 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008400 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008401 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8402 // Currently, all network requests will have the same uids therefore checking the first
8403 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008404 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008405 if (null == uids) {
8406 continue;
8407 }
8408 for (final UidRange range : uids) {
8409 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008410 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008411 highestPriorityNri = nri;
8412 }
James Mattis2516da32021-01-31 17:06:19 -08008413 }
8414 }
8415 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008416 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008417 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008418 }
8419
Varun Ananddf569952019-02-06 10:13:38 -08008420 @Nullable
8421 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8422 return nai != null ? nai.network : null;
8423 }
8424
8425 private void ensureRunningOnConnectivityServiceThread() {
8426 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8427 throw new IllegalStateException(
8428 "Not running on ConnectivityService thread: "
8429 + Thread.currentThread().getName());
8430 }
8431 }
8432
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008433 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008434 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8435 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008436 }
8437
Chalard Jean29d06db2018-05-02 21:14:54 +09008438 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008439 * Returns whether local agents are supported on this device.
8440 *
8441 * Local agents are supported from U on TVs, and from V on all devices.
8442 */
8443 @VisibleForTesting
8444 public boolean areLocalAgentsSupported() {
8445 final PackageManager pm = mContext.getPackageManager();
8446 // Local agents are supported starting on U on TVs and on V on everything else.
8447 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8448 }
8449
8450 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008451 * Register a new agent with ConnectivityService to handle a network.
8452 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008453 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008454 * @param networkInfo the initial info associated with this network. It can be updated later :
8455 * see {@link #updateNetworkInfo}.
8456 * @param linkProperties the initial link properties of this network. They can be updated
8457 * later : see {@link #updateLinkProperties}.
8458 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008459 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008460 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008461 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008462 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008463 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008464 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008465 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008466 public Network registerNetworkAgent(INetworkAgent na,
8467 NetworkInfo networkInfo,
8468 LinkProperties linkProperties,
8469 NetworkCapabilities networkCapabilities,
8470 @NonNull NetworkScore initialScore,
8471 @Nullable LocalNetworkConfig localNetworkConfig,
8472 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008473 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008474 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8475 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8476 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008477 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008478 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008479 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008480 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008481 } else {
8482 enforceNetworkFactoryPermission();
8483 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008484 final boolean hasLocalCap =
8485 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8486 if (hasLocalCap && !areLocalAgentsSupported()) {
8487 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8488 throw new IllegalArgumentException("Local agents are not supported in this version");
8489 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008490 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8491 if (hasLocalCap != hasLocalNetworkConfig) {
8492 throw new IllegalArgumentException(null != localNetworkConfig
8493 ? "Only local network agents can have a LocalNetworkConfig"
8494 : "Local network agents must have a LocalNetworkConfig"
8495 );
8496 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008497
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008498 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008499 final long token = Binder.clearCallingIdentity();
8500 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008501 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008502 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8503 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008504 } finally {
8505 Binder.restoreCallingIdentity(token);
8506 }
8507 }
8508
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008509 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008510 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008511 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8512 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008513 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008514
Chalard Jeandbc46952022-02-02 00:14:18 +09008515 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8516 // and mutate them at any time.
8517 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8518 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8519 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008520 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008521
Chalard Jean366c5252022-01-25 18:27:53 +09008522 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008523 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008524 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8525 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008526 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008527 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008528 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8529 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8530 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008531
Chalard Jeandbc46952022-02-02 00:14:18 +09008532 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008533 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008534 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008535 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008536 mDeps.getNetworkStack().makeNetworkMonitor(
8537 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008538 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8539 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008540 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008541 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008542 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008543 }
8544
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008545 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008546 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008547 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008548 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008549 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008550 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8551 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8552 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008553
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008554 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008555
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008556 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008557 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008558 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008559 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008560
8561 try {
8562 networkMonitor.start();
8563 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008564 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008565 }
Chalard Jean366c5252022-01-25 18:27:53 +09008566
Chalard Jean1e4c2182023-10-06 18:45:53 +09008567 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008568 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008569 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008570 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008571 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008572 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008573 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008574 }
8575
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008576 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8577 @NonNull public final NetworkOffer offer;
8578
8579 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8580 this.offer = offer;
8581 }
8582
8583 @Override
8584 public void binderDied() {
8585 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8586 }
8587 }
8588
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008589 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8590 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8591 if (npi.providerId == providerId) return true;
8592 }
8593 return false;
8594 }
8595
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008596 /**
8597 * Register or update a network offer.
8598 * @param newOffer The new offer. If the callback member is the same as an existing
8599 * offer, it is an update of that offer.
8600 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008601 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008602 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8603 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008604 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008605 // This may actually happen if a provider updates its score or registers and then
8606 // immediately unregisters. The offer would still be in the handler queue, but the
8607 // provider would have been removed.
8608 if (DBG) log("Received offer from an unregistered provider");
8609 return;
8610 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008611 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8612 if (null != existingOffer) {
8613 handleUnregisterNetworkOffer(existingOffer);
8614 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008615 if (DBG) {
8616 // handleUnregisterNetworkOffer has already logged the old offer
8617 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8618 }
8619 } else {
8620 if (DBG) {
8621 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8622 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008623 }
8624 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8625 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008626 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008627 } catch (RemoteException e) {
8628 noi.binderDied();
8629 return;
8630 }
8631 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008632 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008633 }
8634
8635 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8636 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008637 if (DBG) {
8638 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8639 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008640
8641 // If the provider removes the offer and dies immediately afterwards this
8642 // function may be called twice in a row, but the array will no longer contain
8643 // the offer.
8644 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008645 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008646 }
8647
8648 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8649 @NonNull final INetworkOfferCallback callback) {
8650 ensureRunningOnConnectivityServiceThread();
8651 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008652 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008653 }
8654 return null;
8655 }
8656
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008657 /**
8658 * Called when receiving LinkProperties directly from a NetworkAgent.
8659 * Stores into |nai| any data coming from the agent that might also be written to the network's
8660 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8661 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008662 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008663 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008664 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8665 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008666 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008667 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008668 }
8669
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008670 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008671 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008672 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008673
Lorenzo Colittid523d142020-04-01 20:16:30 +09008674 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8675 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8676 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008677 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008678
Suprabh Shukla1e312032023-01-24 03:36:37 -08008679 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008680
8681 // update filtering rules, need to happen after the interface update so netd knows about the
8682 // new interface (the interface name -> index map becomes initialized)
8683 updateVpnFiltering(newLp, oldLp, networkAgent);
8684
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008685 updateMtu(newLp, oldLp);
8686 // TODO - figure out what to do for clat
8687// for (LinkProperties lp : newLp.getStackedLinks()) {
8688// updateMtu(lp, null);
8689// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008690 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008691 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008692 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8693 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008694
Erik Klineb9888902016-04-05 13:30:49 +09008695 updateRoutes(newLp, oldLp, netId);
8696 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008697 // Make sure LinkProperties represents the latest private DNS status.
8698 // This does not need to be done before updateDnses because the
8699 // LinkProperties are not the source of the private DNS configuration.
8700 // updateDnses will fetch the private DNS configuration from DnsManager.
8701 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008702
Chalard Jean5b409c72021-02-04 13:12:59 +09008703 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008704 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008705 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008706 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008707 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008708
8709 updateWakeOnLan(newLp);
8710
Hai Shalome58bdc62021-01-11 18:45:34 -08008711 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8712 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8713 // does, it needs to be merged here.
8714 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8715 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008716
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008717 // TODO - move this check to cover the whole function
8718 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008719 synchronized (networkAgent) {
8720 networkAgent.linkProperties = newLp;
8721 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008722 // Start or stop DNS64 detection and 464xlat according to network state.
8723 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008724 // Notify NSS when relevant events happened. Currently, NSS only cares about
8725 // interface changed to update clat interfaces accounting.
8726 final boolean interfacesChanged = oldLp == null
8727 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8728 if (interfacesChanged) {
8729 notifyIfacesChangedForNetworkStats();
8730 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008731 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8732 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008733 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008734 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008735
8736 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008737 }
8738
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008739 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8740 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8741 }
8742
Hai Shalome58bdc62021-01-11 18:45:34 -08008743 /**
8744 * @param naData captive portal data from NetworkAgent
8745 * @param apiData captive portal data from capport API
8746 */
8747 @Nullable
8748 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8749 CaptivePortalData apiData) {
8750 if (naData == null || apiData == null) {
8751 return naData == null ? apiData : naData;
8752 }
8753 final CaptivePortalData.Builder captivePortalBuilder =
8754 new CaptivePortalData.Builder(naData);
8755
8756 if (apiData.isCaptive()) {
8757 captivePortalBuilder.setCaptive(true);
8758 }
8759 if (apiData.isSessionExtendable()) {
8760 captivePortalBuilder.setSessionExtendable(true);
8761 }
8762 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8763 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8764 // otherwise data would be inconsistent. Prefer the capport API info if present,
8765 // as it can generally be refreshed more often.
8766 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8767 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8768 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8769 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8770 // No source has time / bytes remaining information: surface the newest refresh time
8771 // for other fields
8772 captivePortalBuilder.setRefreshTime(
8773 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8774 }
8775
Hai Shalom7c6ab402021-02-04 19:34:06 -08008776 // Prioritize the user portal URL from the network agent if the source is authenticated.
8777 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8778 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8779 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8780 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008781 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008782 // Prioritize the venue information URL from the network agent if the source is
8783 // authenticated.
8784 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8785 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8786 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8787 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008788 }
8789 return captivePortalBuilder.build();
8790 }
8791
Suprabh Shukla53e16392023-04-26 18:47:36 -07008792 @VisibleForTesting
8793 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008794 // This needs to be kept in sync and backwards compatible with the decoding logic in
8795 // NetdEventListenerService, which is non-mainline code.
8796 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8797 }
8798
Suprabh Shukla75642282023-04-25 23:15:43 -07008799 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8800 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8801 return true;
8802 }
8803 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8804 return true;
8805 }
8806 return false;
8807 }
8808
Suprabh Shukla1e312032023-01-24 03:36:37 -08008809 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008810 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008811 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008812 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008813 return;
8814 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008815
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008816 // Mask/mark of zero will not detect anything interesting.
8817 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008818 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008819 return;
8820 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008821
Suprabh Shukla1e312032023-01-24 03:36:37 -08008822 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008823 try {
8824 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008825 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008826 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008827 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008828 }
8829 } catch (Exception e) {
8830 loge("Exception modifying wakeup packet monitoring: " + e);
8831 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008832 }
8833
Junyu Lai970963e2022-10-25 15:46:47 +08008834 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008835 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008836 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008837 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008838 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008839 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008840 for (final String iface : interfaceDiff.added) {
8841 try {
8842 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008843 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008844 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008845 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008846 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008847 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008848 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008849 }
Paul Jensenbff73492014-04-28 10:33:11 -04008850 }
8851 }
Chalard Jean9589e722019-11-19 19:03:53 +09008852 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008853 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008854 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008855 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008856 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008857 } catch (Exception e) {
8858 loge("Exception removing interface: " + e);
8859 }
8860 }
8861 }
8862
Paul Jensene0fd4a82014-08-06 15:51:33 -04008863 /**
8864 * Have netd update routes from oldLp to newLp.
8865 * @return true if routes changed between oldLp and newLp
8866 */
Junyu Lai970963e2022-10-25 15:46:47 +08008867 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8868 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008869 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008870 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8871 new CompareOrUpdateResult<>(
8872 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008873 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008874 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008875
8876 // add routes before removing old in case it helps with continuous connectivity
8877
Chalard Jean9dd11612018-06-04 16:52:49 +09008878 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008879 for (RouteInfo route : routeDiff.added) {
8880 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008881 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008882 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008883 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008884 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008885 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008886 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008887 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008888 }
8889 }
8890 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008891 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008892 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008893 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008894 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008895 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008896 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008897 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008898 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008899 }
8900 }
8901
8902 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008903 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008904 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008905 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008906 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008907 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008908 }
8909 }
Tyler Weare4314862019-12-05 14:55:30 -08008910
8911 for (RouteInfo route : routeDiff.updated) {
8912 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8913 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008914 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008915 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008916 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008917 }
8918 }
8919 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8920 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008921 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008922
Junyu Lai970963e2022-10-25 15:46:47 +08008923 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8924 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008925 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8926 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008927 }
Erik Klineb9888902016-04-05 13:30:49 +09008928
Erik Kline31b4a9e2018-01-11 21:07:29 +09008929 if (DBG) {
8930 final Collection<InetAddress> dnses = newLp.getDnsServers();
8931 log("Setting DNS servers for network " + netId + " to " + dnses);
8932 }
Erik Klineb9888902016-04-05 13:30:49 +09008933 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008934 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008935 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008936 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008937 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008938 }
Erik Kline54e35c02017-04-07 15:29:29 +09008939 }
8940
Junyu Lai970963e2022-10-25 15:46:47 +08008941 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8942 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008943 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8944 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008945 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8946 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008947
8948 if (!wasFiltering && !needsFiltering) {
8949 // Nothing to do.
8950 return;
8951 }
8952
8953 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8954 // Nothing changed.
8955 return;
8956 }
8957
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008958 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008959 if (ranges == null || ranges.isEmpty()) {
8960 return;
8961 }
8962
Qingxi Libb8da982020-01-17 17:54:27 -08008963 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008964 // TODO: this create a window of opportunity for apps to receive traffic between the time
8965 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008966 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008967 // old rules are being removed.
8968 if (wasFiltering) {
8969 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8970 }
8971 if (needsFiltering) {
8972 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8973 }
8974 }
8975
Valentin Iftime9fa35092019-09-24 13:32:13 +02008976 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008977 if (mWolSupportedInterfaces == null) {
8978 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008979 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008980 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008981 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8982 }
8983
Luke Huangb913c812018-08-24 20:33:16 +08008984 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008985 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008986 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008987 }
8988 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008989 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008990 }
Luke Huangb913c812018-08-24 20:33:16 +08008991 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008992 }
8993
Chalard Jean62edfd82019-12-02 18:39:29 +09008994 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8995 @NonNull final NetworkCapabilities newNc) {
8996 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8997 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008998 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008999 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08009000 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08009001 } catch (RemoteException | ServiceSpecificException e) {
9002 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09009003 }
9004 }
9005 }
9006
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009007 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009008 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09009009 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009010 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08009011 underlyingNetworks = underlyingNetworksOrDefault(
9012 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09009013 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009014 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
9015 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009016 // metered if any underlying is metered, or originally declared metered by the agent.
9017 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009018 boolean roaming = false; // roaming if any underlying is roaming
9019 boolean congested = false; // congested if any underlying is congested
9020 boolean suspended = true; // suspended if all underlying are suspended
9021
9022 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08009023 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009024 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08009025 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009026 for (Network underlyingNetwork : underlyingNetworks) {
9027 final NetworkAgentInfo underlying =
9028 getNetworkAgentInfoForNetwork(underlyingNetwork);
9029 if (underlying == null) continue;
9030
9031 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
9032 hadUnderlyingNetworks = true;
9033 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09009034 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009035 }
9036
9037 // Merge capabilities of this underlying network. For bandwidth, assume the
9038 // worst case.
9039 downKbps = NetworkCapabilities.minBandwidth(downKbps,
9040 underlyingCaps.getLinkDownstreamBandwidthKbps());
9041 upKbps = NetworkCapabilities.minBandwidth(upKbps,
9042 underlyingCaps.getLinkUpstreamBandwidthKbps());
9043 // If this underlying network is metered, the VPN is metered (it may cost money
9044 // to send packets on this network).
9045 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
9046 // If this underlying network is roaming, the VPN is roaming (the billing structure
9047 // is different than the usual, local one).
9048 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9049 // If this underlying network is congested, the VPN is congested (the current
9050 // condition of the network affects the performance of this network).
9051 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
9052 // If this network is not suspended, the VPN is not suspended (the VPN
9053 // is able to transfer some data).
9054 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08009055 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009056 }
9057 }
9058 if (!hadUnderlyingNetworks) {
9059 // No idea what the underlying networks are; assume reasonable defaults
9060 metered = true;
9061 roaming = false;
9062 congested = false;
9063 suspended = false;
9064 }
9065
Chalard Jean1d420b32022-10-12 16:39:37 +09009066 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009067 newNc.setLinkDownstreamBandwidthKbps(downKbps);
9068 newNc.setLinkUpstreamBandwidthKbps(upKbps);
9069 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
9070 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
9071 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
9072 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08009073 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009074 }
9075
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009076 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009077 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
9078 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
9079 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04009080 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09009081 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009082 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09009083 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09009084 // Don't complain for VPNs since they're not driven by requests and there is no risk of
9085 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009086 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09009087 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09009088 if (nai.everConnected()
9089 && !nai.isVPN()
9090 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009091 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09009092 // does not cause any request (that is not a listen) currently matching that agent to
9093 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009094 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09009095 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009096 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09009097 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009098 }
9099
Paul Jensen53f08952015-06-16 14:27:36 -04009100 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009101 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09009102 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009103 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04009104 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009105 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04009106 }
Chalard Jean254bd162022-08-25 13:04:51 +09009107 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009108 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009109 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009110 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009111 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009112 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009113 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009114 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009115 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009116 }
Chalard Jean254bd162022-08-25 13:04:51 +09009117 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08009118 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9119 } else {
9120 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9121 }
lucasline117e2e2019-10-22 18:27:33 +08009122 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009123
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009124 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09009125 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
9126 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009127 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09009128 }
9129
Lorenzo Colittibd079452021-07-02 11:47:57 +09009130 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09009131 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09009132 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009133 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009134 }
9135
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009136 return newNc;
9137 }
9138
Lorenzo Colitti44840702021-01-11 22:27:57 +09009139 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
9140 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
9141 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9142 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9143 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9144 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9145 if (prevSuspended != suspended) {
9146 // TODO (b/73132094) : remove this call once the few users of onSuspended and
9147 // onResumed have been removed.
9148 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
9149 : ConnectivityManager.CALLBACK_RESUMED);
9150 }
9151 if (prevSuspended != suspended || prevRoaming != roaming) {
9152 // updateNetworkInfo will mix in the suspended info from the capabilities and
9153 // take appropriate action for the network having possibly changed state.
9154 updateNetworkInfo(nai, nai.networkInfo);
9155 }
9156 }
9157
Ying Xu7cabd322024-01-15 18:40:15 -08009158 private void handleUidCarrierPrivilegesLost(int uid) {
9159 ensureRunningOnConnectivityServiceThread();
9160 // A NetworkRequest needs to be revoked when all the conditions are met
9161 // 1. It requests restricted network
9162 // 2. The requestor uid matches the uid with the callback
9163 // 3. The app doesn't have Carrier Privileges
9164 // 4. The app doesn't have permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS
9165 for (final NetworkRequest nr : mNetworkRequests.keySet()) {
9166 if ((nr.isRequest() || nr.isListen())
9167 && !nr.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
9168 && nr.getRequestorUid() == uid
9169 && !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) {
9177 if (nai.networkCapabilities.getAllowedUidsNoCopy().contains(uid)) {
9178 final NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
9179 NetworkAgentInfo.restrictCapabilitiesFromNetworkAgent(
9180 nc,
9181 uid,
9182 false /* hasAutomotiveFeature (irrelevant) */,
9183 mDeps,
9184 mCarrierPrivilegeAuthenticator);
9185 updateCapabilities(nai.getScore(), nai, nc);
9186 }
9187 }
9188 }
9189
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009190 /**
9191 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
9192 *
9193 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
9194 * capabilities we manage and store in {@code nai}, such as validated status and captive
9195 * portal status)
9196 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
9197 * potentially triggers rematches.
9198 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
9199 * change.)
9200 *
9201 * @param oldScore score of the network before any of the changes that prompted us
9202 * to call this function.
9203 * @param nai the network having its capabilities updated.
9204 * @param nc the new network capabilities.
9205 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009206 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09009207 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009208 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009209 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009210 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9211 if (null != differences) {
9212 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9213 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009214 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009215 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009216
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009217 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009218 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009219 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009220
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009221 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009222 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9223 // the change we're processing can't affect any requests, it can only affect the listens
9224 // on this network. We might have been called by rematchNetworkAndRequests when a
9225 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009226 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009227 } else {
9228 // If the requestable capabilities have changed or the score changed, we can't have been
9229 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009230 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009231 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009232 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009233 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009234
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009235 final boolean oldMetered = prevNc.isMetered();
9236 final boolean newMetered = newNc.isMetered();
9237 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009238
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009239 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009240 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9241 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009242 }
junyulaif2c67e42018-08-07 19:50:45 +08009243
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009244 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9245 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009246
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009247 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009248 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009249 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009250 }
9251
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009252 // This network might have been underlying another network. Propagate its capabilities.
9253 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009254
Ken Chen5a35cf92023-10-07 07:54:22 +08009255 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009256 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009257 }
lucaslin53e8a262021-06-08 01:43:59 +08009258
9259 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009260 }
9261
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009262 /** Convenience method to update the capabilities for a given network. */
9263 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009264 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009265 }
9266
Yang Sun29037f62023-12-04 10:31:58 +08009267 private void maybeApplyMulticastRoutingConfig(@NonNull final NetworkAgentInfo nai,
9268 final LocalNetworkConfig oldConfig,
9269 final LocalNetworkConfig newConfig) {
9270 final MulticastRoutingConfig oldUpstreamConfig =
9271 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9272 oldConfig.getUpstreamMulticastRoutingConfig();
9273 final MulticastRoutingConfig oldDownstreamConfig =
9274 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9275 oldConfig.getDownstreamMulticastRoutingConfig();
9276 final MulticastRoutingConfig newUpstreamConfig =
9277 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9278 newConfig.getUpstreamMulticastRoutingConfig();
9279 final MulticastRoutingConfig newDownstreamConfig =
9280 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9281 newConfig.getDownstreamMulticastRoutingConfig();
9282
9283 if (oldUpstreamConfig.equals(newUpstreamConfig) &&
9284 oldDownstreamConfig.equals(newDownstreamConfig)) {
9285 return;
9286 }
9287
9288 final String downstreamNetworkName = nai.linkProperties.getInterfaceName();
9289 final LocalNetworkInfo lni = localNetworkInfoForNai(nai);
9290 final Network upstreamNetwork = lni.getUpstreamNetwork();
9291
9292 if (upstreamNetwork != null) {
9293 final String upstreamNetworkName =
9294 getLinkProperties(upstreamNetwork).getInterfaceName();
9295 applyMulticastRoutingConfig(downstreamNetworkName, upstreamNetworkName, newConfig);
9296 }
9297 }
9298
9299 private void applyMulticastRoutingConfig(@NonNull String localNetworkInterfaceName,
9300 @NonNull String upstreamNetworkInterfaceName,
9301 @NonNull final LocalNetworkConfig config) {
Yang Sunca537d52024-01-19 12:53:50 +08009302 if (mMulticastRoutingCoordinatorService == null) {
9303 if (config.getDownstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE ||
9304 config.getUpstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE) {
9305 loge("Multicast routing is not supported, failed to configure " + config
9306 + " for " + localNetworkInterfaceName + " to "
9307 + upstreamNetworkInterfaceName);
9308 }
9309 return;
9310 }
Yang Sun29037f62023-12-04 10:31:58 +08009311
9312 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9313 upstreamNetworkInterfaceName, config.getUpstreamMulticastRoutingConfig());
9314 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9315 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9316 config.getDownstreamMulticastRoutingConfig());
9317 }
9318
9319 private void disableMulticastRouting(@NonNull String localNetworkInterfaceName,
9320 @NonNull String upstreamNetworkInterfaceName) {
Yang Sunca537d52024-01-19 12:53:50 +08009321 if (mMulticastRoutingCoordinatorService == null) {
9322 return;
9323 }
Yang Sun29037f62023-12-04 10:31:58 +08009324
9325 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9326 upstreamNetworkInterfaceName, MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9327 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9328 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9329 MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9330 }
9331
Chalard Jean1e4c2182023-10-06 18:45:53 +09009332 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009333 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009334 @Nullable final LocalNetworkConfig oldConfig,
9335 @NonNull final LocalNetworkConfig newConfig) {
9336 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009337 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9338 return;
9339 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009340
Chalard Jean4fe23392023-10-17 23:02:27 +09009341 if (VDBG) {
9342 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9343 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009344 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
Chalard Jean1e4c2182023-10-06 18:45:53 +09009345 configBuilder.setUpstreamMulticastRoutingConfig(
9346 newConfig.getUpstreamMulticastRoutingConfig());
9347 configBuilder.setDownstreamMulticastRoutingConfig(
9348 newConfig.getDownstreamMulticastRoutingConfig());
9349
9350 final NetworkRequest oldRequest =
9351 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9352 final NetworkCapabilities oldCaps =
9353 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9354 final NetworkRequestInfo oldNri =
9355 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9356 final NetworkAgentInfo oldSatisfier =
9357 null == oldNri ? null : oldNri.getSatisfier();
9358 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9359 final NetworkCapabilities newCaps =
9360 (null == newRequest) ? null : newRequest.networkCapabilities;
9361 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9362 if (null != oldRequest && requestUpdated) {
9363 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9364 if (null == newRequest && null != oldSatisfier) {
9365 // If there is an old satisfier, but no new request, then remove the old upstream.
9366 removeLocalNetworkUpstream(nai, oldSatisfier);
9367 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009368 // When there is a new request, the rematch sees the new request and sends the
9369 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9370 // But here there is no new request, so the rematch won't see anything. Send
9371 // callbacks to apps now to tell them about the loss of upstream.
9372 notifyNetworkCallbacks(nai,
9373 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009374 return;
9375 }
9376 }
9377 if (null != newRequest && requestUpdated) {
9378 // File the new request if :
9379 // - it has changed (requestUpdated), or
9380 // - it's the first time this local info (null == oldConfig)
9381 // is updated and the request has not been filed yet.
9382 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9383 // upstream (the best) but never request it to be brought up.
9384 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9385 nextNetworkRequestId(), LISTEN_FOR_BEST);
9386 configBuilder.setUpstreamSelector(nr);
9387 final NetworkRequestInfo nri = new NetworkRequestInfo(
9388 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9389 0 /* callbackFlags */, null /* attributionTag */);
9390 if (null != oldSatisfier) {
9391 // Set the old satisfier in the new NRI so that the rematch will see any changes
9392 nri.setSatisfier(oldSatisfier, nr);
9393 }
9394 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009395 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9396 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9397 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009398 handleRegisterNetworkRequest(nri);
9399 } else {
9400 configBuilder.setUpstreamSelector(oldRequest);
9401 nai.localNetworkConfig = configBuilder.build();
9402 }
Yang Sun29037f62023-12-04 10:31:58 +08009403 maybeApplyMulticastRoutingConfig(nai, oldConfig, newConfig);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009404 }
9405
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009406 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009407 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009408 *
9409 * Ingress interface filtering enforces that all apps under the given network can only receive
9410 * packets from the network's interface (and loopback). This is important for VPNs because
9411 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9412 * non-VPN interfaces.
9413 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009414 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009415 * 1. the network is an app VPN (not legacy VPN)
9416 * 2. the VPN does not allow bypass
9417 * 3. the VPN is fully-routed
9418 * 4. the VPN interface is non-null
9419 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009420 * @see INetd#firewallAddUidInterfaceRules
9421 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009422 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009423 @Nullable
9424 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009425 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009426 if (nc == null || lp == null) return null;
9427 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009428 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009429 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009430 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009431 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009432 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009433 && !lp.hasExcludeRoute()) {
9434 return lp.getInterfaceName();
9435 }
9436 return null;
9437 }
9438
9439 /**
9440 * Returns whether we need to set interface filtering rule or not
9441 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009442 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009443 String isolationIface) {
9444 // Allow rules are always needed if VPN isolation is enabled.
9445 if (isolationIface != null) return true;
9446
9447 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9448 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9449 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009450 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009451 }
9452
Chiachang Wang28afaff2020-12-10 22:24:47 +08009453 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9454 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9455 int index = 0;
9456 for (UidRange range : ranges) {
9457 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9458 index++;
9459 }
9460 return stableRanges;
9461 }
9462
Chalard Jeane6c95272022-01-25 21:04:21 +09009463 private static UidRangeParcel[] intsToUidRangeStableParcels(
9464 final @NonNull ArraySet<Integer> uids) {
9465 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9466 int index = 0;
9467 for (int uid : uids) {
9468 stableRanges[index] = new UidRangeParcel(uid, uid);
9469 index++;
9470 }
9471 return stableRanges;
9472 }
9473
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009474 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9475 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9476 for (int i = 0; i < ranges.length; i++) {
9477 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9478 }
9479 return stableRanges;
9480 }
9481
Motomu Utsumi93a22182023-03-16 17:04:21 +09009482 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009483 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009484 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9485 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009486 if (mDeps.isAtLeastU()) {
9487 final Set<Integer> exemptUidSet = new ArraySet<>();
9488 for (final int uid: exemptUids) {
9489 exemptUidSet.add(uid);
9490 }
9491 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9492 } else {
9493 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9494 }
Ken Chen5e65a852020-12-24 12:59:10 +08009495 } catch (Exception e) {
9496 loge("Exception in socket destroy: ", e);
9497 }
9498 }
9499 }
9500
paulhuaa0743d2021-05-26 21:56:03 +08009501 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009502 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009503 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9504 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9505 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009506 exemptUids[0] = VPN_UID;
9507 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009508 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9509
Motomu Utsumi6345e462023-03-13 13:24:50 +09009510 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009511 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009512 try {
9513 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009514 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009515 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009516 } else {
paulhu0e79d952021-06-09 16:11:35 +08009517 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009518 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009519 }
9520 } catch (Exception e) {
9521 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9522 " on netId " + nai.network.netId + ". " + e);
9523 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009524 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009525 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009526 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009527
lucaslin53e8a262021-06-08 01:43:59 +08009528 private boolean isProxySetOnAnyDefaultNetwork() {
9529 ensureRunningOnConnectivityServiceThread();
9530 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9531 final NetworkAgentInfo nai = nri.getSatisfier();
9532 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9533 return true;
9534 }
9535 }
9536 return false;
9537 }
9538
9539 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9540 NetworkCapabilities newNc) {
9541 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9542 // the proxy might be changed since the default network satisfied by the apps might also
9543 // changed.
9544 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9545 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009546 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9547 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009548 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009549 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9550 mProxyTracker.sendProxyBroadcast();
9551 }
9552 }
9553
Chalard Jeane6c95272022-01-25 21:04:21 +09009554 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9555 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009556 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9557 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009558 if (null == prevRanges) prevRanges = new ArraySet<>();
9559 if (null == newRanges) newRanges = new ArraySet<>();
9560 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9561
9562 prevRanges.removeAll(newRanges);
9563 newRanges.removeAll(prevRangesCopy);
9564
9565 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009566 // When updating the VPN uid routing rules, add the new range first then remove the old
9567 // range. If old range were removed first, there would be a window between the old
9568 // range being removed and the new range being added, during which UIDs contained
9569 // in both ranges are not subject to any VPN routing rules. Adding new range before
9570 // removing old range works because, unlike the filtering rules below, it's possible to
9571 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009572 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9573 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9574 // [1-5] & [1-2],[4-5] == [3]
9575 // Then we can do:
9576 // maybeCloseSockets([3])
9577 // mNetd.networkAddUidRanges([1-2],[4-5])
9578 // mNetd.networkRemoveUidRanges([1-5])
9579 // maybeCloseSockets([3])
9580 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9581 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009582 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009583 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009584 }
9585 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009586 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009587 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009588 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9589 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009590 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9591 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009592 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009593 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009594 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9595 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9596 // were added first and then newRanges got removed later, there would be only one uid
9597 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9598 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9599 // Note that this is in contrast with the (more robust) update of VPN routing rules
9600 // above, where the addition of new ranges happens before the removal of old ranges.
9601 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9602 // to be removed will never overlap with the new range to be added.
9603 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009604 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9605 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009606 }
9607 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009608 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009609 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009610 } catch (Exception e) {
9611 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009612 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009613 }
9614 }
9615
Chalard Jeande665262022-02-25 16:12:12 +09009616 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009617 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9618 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009619 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9620 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009621 if (prevEmpty && newEmpty) return;
9622
9623 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009624 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009625 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009626 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009627
9628 if (prevUids.equals(newUids)) return;
9629
9630 // This implementation is very simple and vastly faster for sets of Integers than
9631 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9632 // a key computed from the value and has storage for that.
9633 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9634 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9635 toRemove.removeAll(newUids);
9636 toAdd.removeAll(prevUids);
Chalard Jeane6c95272022-01-25 21:04:21 +09009637 try {
9638 if (!toAdd.isEmpty()) {
9639 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9640 nai.network.netId,
9641 intsToUidRangeStableParcels(toAdd),
9642 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9643 }
9644 if (!toRemove.isEmpty()) {
9645 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9646 nai.network.netId,
9647 intsToUidRangeStableParcels(toRemove),
9648 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9649 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009650 } catch (ServiceSpecificException e) {
9651 // Has the interface disappeared since the network was built ?
9652 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009653 } catch (RemoteException e) {
9654 // Netd died. This usually causes a runtime restart anyway.
9655 }
9656 }
9657
Junyu Lai2ed7d412022-10-07 16:52:21 +08009658 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9659 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009660 ensureRunningOnConnectivityServiceThread();
9661
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009662 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009663 // Ignore updates for disconnected networks
9664 return;
9665 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009666 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009667 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009668 + "; created=" + nai.getCreatedTime()
9669 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009670 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009671 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9672 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009673 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009674 }
9675
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009676 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9677 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009678 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009679 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009680 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009681 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9682 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9683 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009684 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9685 // need to be sent as a separate extra.
9686 final NetworkRequest req = nri.isMultilayerRequest()
9687 ? nri.getActiveRequest()
9688 // Non-multilayer listen requests do not have an active request
9689 : nri.mRequests.get(0);
9690 if (req == null) {
9691 Log.wtf(TAG, "No request in NRI " + nri);
9692 }
9693 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009694 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009695 sendIntent(nri.mPendingIntent, intent);
9696 }
9697 // else not handled
9698 }
9699
Michael Groover73f69482023-01-27 11:01:25 -06009700 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9701 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009702 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9703 mPendingIntentWakeLock.acquire();
9704 try {
9705 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009706 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009707 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009708 // Explicitly disallow the receiver from starting activities, to prevent apps from
9709 // utilizing the PendingIntent as a backdoor to do this.
9710 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9711 }
9712 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9713 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009714 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009715 } catch (PendingIntent.CanceledException e) {
9716 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9717 mPendingIntentWakeLock.release();
9718 releasePendingNetworkRequest(pendingIntent);
9719 }
9720 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9721 }
9722
9723 @Override
9724 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9725 String resultData, Bundle resultExtras) {
9726 if (DBG) log("Finished sending " + pendingIntent);
9727 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009728 // Release with a delay so the receiving client has an opportunity to put in its
9729 // own request.
9730 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009731 }
9732
Chalard Jean22350c92023-10-07 19:21:45 +09009733 @Nullable
9734 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9735 if (!nai.isLocalNetwork()) return null;
9736 final Network upstream;
9737 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9738 if (null == selector) {
9739 upstream = null;
9740 } else {
9741 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9742 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9743 upstream = (null == satisfier) ? null : satisfier.network;
9744 }
9745 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9746 }
9747
Chalard Jean46bfbf02022-02-02 00:56:25 +09009748 // networkAgent is only allowed to be null if notificationType is
9749 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9750 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009751 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009752 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009753 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009754 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009755 // Default request has no msgr. Also prevents callbacks from being invoked for
9756 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9757 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9758 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009759 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009760 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009761 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009762 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009763 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009764 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009765 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009766 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9767 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009768 }
Roshan Pius951c0032020-12-22 15:10:42 -08009769 final boolean includeLocationSensitiveInfo =
9770 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009771 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009772 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009773 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009774 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009775 networkCapabilitiesRestrictedForCallerPermissions(
9776 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9777 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009778 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009779 nri.mCallingAttributionTag);
9780 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009781 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9782 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009783 // The local network info is often null, so can't use the static putParcelable
9784 // method here.
9785 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9786 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009787 // For this notification, arg1 contains the blocked status.
9788 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009789 break;
9790 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009791 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009792 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009793 break;
9794 }
9795 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009796 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009797 final NetworkCapabilities netCap =
9798 networkCapabilitiesRestrictedForCallerPermissions(
9799 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9800 putParcelable(
9801 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009802 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009803 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009804 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009805 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009806 break;
9807 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009808 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009809 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9810 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009811 break;
9812 }
junyulaif2c67e42018-08-07 19:50:45 +08009813 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009814 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009815 msg.arg1 = arg1;
9816 break;
9817 }
Chalard Jean22350c92023-10-07 19:21:45 +09009818 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9819 if (!networkAgent.isLocalNetwork()) {
9820 Log.wtf(TAG, "Callback for local info for a non-local network");
9821 return;
9822 }
9823 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9824 break;
9825 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009826 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009827 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009828 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009829 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009830 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009831 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009832 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009833 }
James Mattis45d81842021-01-10 14:24:24 -08009834 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009835 } catch (RemoteException e) {
9836 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009837 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009838 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009839 }
9840
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009841 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9842 bundle.putParcelable(t.getClass().getSimpleName(), t);
9843 }
9844
Chalard Jean0702f982021-09-16 21:50:07 +09009845 /**
9846 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9847 *
9848 * When a request should be assigned to a new network, it is normally lingered to give
9849 * time for apps to gracefully migrate their connections. When both networks are on the same
9850 * radio, but that radio can't do time-sharing efficiently, this may end up being
9851 * counter-productive because any traffic on the old network may drastically reduce the
9852 * performance of the new network.
9853 * The stack supports a configuration to let modem vendors state that their radio can't
9854 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9855 * from one cell network to another can't be done gracefully.
9856 *
9857 * @param oldNai the old network serving the request
9858 * @param newNai the new network serving the request
9859 * @return whether the switch can be graceful
9860 */
9861 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9862 @NonNull final NetworkAgentInfo newSatisfier) {
9863 if (mCellularRadioTimesharingCapable) return true;
9864 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9865 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9866 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9867 }
9868
Paul Jensenaf94b982014-09-30 15:37:41 -04009869 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009870 if (nai.numRequestNetworkRequests() != 0) {
9871 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9872 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009873 // Ignore listening and track default requests.
9874 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009875 loge("Dead network still had at least " + nr);
9876 break;
9877 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009878 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009879 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009880 }
9881
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009882 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9883 if (oldNetwork == null) {
9884 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9885 return;
9886 }
Chalard Jean49707572019-12-10 21:07:02 +09009887 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009888
9889 // If we get here it means that the last linger timeout for this network expired. So there
9890 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009891 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009892
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009893 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009894 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009895 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009896 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009897 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009898 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009899 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009900 }
9901
James Mattise3ef1912020-12-20 11:09:58 -08009902 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9903 boolean isDefaultChanged = false;
9904 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9905 final NetworkReassignment.RequestReassignment reassignment =
9906 changes.getReassignment(defaultRequestInfo);
9907 if (null == reassignment) {
9908 continue;
9909 }
9910 // reassignment only contains those instances where the satisfying network changed.
9911 isDefaultChanged = true;
9912 // Notify system services of the new default.
9913 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9914 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009915
James Mattise3ef1912020-12-20 11:09:58 -08009916 if (isDefaultChanged) {
9917 // Hold a wakelock for a short time to help apps in migrating to a new default.
9918 scheduleReleaseNetworkTransitionWakelock();
9919 }
9920 }
9921
Aaron Huang9fe47be2021-06-08 13:11:45 +08009922 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9923 if (null == oldDefaultNetwork) return;
9924 // The network stopped being the default. If it was using a PAC proxy, then the
9925 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9926 // to the local proxy server, which would forward them over the newly default network.
9927 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9928 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9929 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9930 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9931 }
9932
James Mattise3ef1912020-12-20 11:09:58 -08009933 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9934 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9935 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9936 if (DBG) {
9937 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9938 }
Chalard Jean8e382112019-12-03 20:45:30 +09009939
James Mattisd31bdfa2020-12-23 16:37:26 -08009940 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9941 if (newDefaultNetwork != null) {
9942 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009943 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009944
James Mattisd31bdfa2020-12-23 16:37:26 -08009945 // Set an app level managed default and return since further processing only applies to the
9946 // default network.
9947 if (mDefaultRequest != nri) {
9948 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9949 return;
9950 }
9951
9952 makeDefaultNetwork(newDefaultNetwork);
9953
James Mattise3ef1912020-12-20 11:09:58 -08009954 if (oldDefaultNetwork != null) {
9955 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9956 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009957 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009958 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009959 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009960 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009961 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009962 updateTcpBufferSizes(null != newDefaultNetwork
9963 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009964 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009965 }
9966
James Mattisd31bdfa2020-12-23 16:37:26 -08009967 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9968 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9969 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9970 try {
9971 if (VDBG) {
9972 log("Setting default network for " + nri
9973 + " using UIDs " + nri.getUids()
9974 + " with old network " + (oldDefaultNetwork != null
9975 ? oldDefaultNetwork.network().getNetId() : "null")
9976 + " and new network " + (newDefaultNetwork != null
9977 ? newDefaultNetwork.network().getNetId() : "null"));
9978 }
9979 if (nri.getUids().isEmpty()) {
9980 throw new IllegalStateException("makeDefaultForApps called without specifying"
9981 + " any applications to set as the default." + nri);
9982 }
9983 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009984 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009985 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009986 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009987 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009988 }
9989 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009990 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009991 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009992 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009993 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009994 }
9995 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009996 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009997 }
9998 }
9999
Junyu Lai35665cc2022-12-19 17:37:48 +080010000 /**
10001 * Collect restricted uid ranges for the given network and UserHandle, these uids
10002 * are not restricted for matched enterprise networks but being restricted for non-matched
10003 * enterprise networks and non-enterprise networks.
10004 */
10005 @NonNull
10006 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
10007 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
10008 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
10009 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
10010 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
10011
10012 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
10013 // The NC is built from a `ProfileNetworkPreference` which has only one
10014 // enterprise ID, so it's guaranteed to have exactly one.
10015 final int prefId = pref.capabilities.getEnterpriseIds()[0];
10016 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
10017 continue;
10018 }
10019 }
10020
10021 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
10022 pref.capabilities.getUidRanges())) {
10023 throw new IllegalArgumentException(
10024 "Overlapping uid range in preference: " + pref);
10025 }
10026 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
10027 }
10028 return restrictedUidRanges;
10029 }
10030
10031 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +080010032 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +090010033 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +080010034
Junyu Lai35665cc2022-12-19 17:37:48 +080010035 ensureRunningOnConnectivityServiceThread();
10036 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
10037 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
10038 .getUserHandles(true /* excludeDying */);
10039 if (users.isEmpty()) {
10040 throw new IllegalStateException("No user is available");
10041 }
10042
10043 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10044 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
10045 for (final UserHandle user : users) {
10046 final ArraySet<UidRange> restrictedUidRanges =
10047 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
10048 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
10049 UidRange.createForUser(user), restrictedUidRanges));
10050 }
10051
10052 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
10053 configs.add(new NativeUidRangeConfig(
10054 nai.network.netId, rangesParcel, 0 /* subPriority */));
10055 }
10056
10057 // The netd API replaces the previous configs with the current configs.
10058 // Thus, for network disconnection or preference removal, no need to
10059 // unset previous config. Instead, collecting all currently needed
10060 // configs and issue to netd.
10061 try {
10062 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
10063 } catch (ServiceSpecificException e) {
10064 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +080010065 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +080010066 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +080010067 // Netd died. This will cause a runtime restart anyway.
10068 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +080010069 }
10070 }
10071
James Mattisd31bdfa2020-12-23 16:37:26 -080010072 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
10073 try {
10074 if (null != newDefaultNetwork) {
10075 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
10076 } else {
10077 mNetd.networkClearDefault();
10078 }
10079 } catch (RemoteException | ServiceSpecificException e) {
10080 loge("Exception setting default network :" + e);
10081 }
10082 }
10083
Chalard Jean05cbe972019-12-09 11:50:38 +090010084 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010085 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +090010086 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +090010087 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +090010088 processNewlySatisfiedListenRequests(nai);
10089 }
10090
10091 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -080010092 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10093 if (nri.isMultilayerRequest()) {
10094 continue;
10095 }
10096 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010097 if (!nr.isListen()) continue;
10098 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -080010099 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010100 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
10101 }
10102 }
Chalard Jeancd397a22019-11-22 22:33:33 +090010103 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010104
Chalard Jeancd397a22019-11-22 22:33:33 +090010105 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -080010106 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10107 if (nri.isMultilayerRequest()) {
10108 continue;
10109 }
10110 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010111 if (!nr.isListen()) continue;
10112 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
10113 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +090010114 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010115 }
10116 }
10117 }
10118
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010119 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010120 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010121 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -080010122 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +090010123 @Nullable public final NetworkRequest mOldNetworkRequest;
10124 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010125 @Nullable public final NetworkAgentInfo mOldNetwork;
10126 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -080010127 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010128 @Nullable final NetworkRequest oldNetworkRequest,
10129 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010130 @Nullable final NetworkAgentInfo oldNetwork,
10131 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010132 mNetworkRequestInfo = networkRequestInfo;
10133 mOldNetworkRequest = oldNetworkRequest;
10134 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010135 mOldNetwork = oldNetwork;
10136 mNewNetwork = newNetwork;
10137 }
Chalard Jean49707572019-12-10 21:07:02 +090010138
10139 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +090010140 final NetworkRequest requestToShow = null != mNewNetworkRequest
10141 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
10142 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -080010143 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
10144 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +090010145 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010146 }
10147
Chalard Jean46a62372019-12-10 21:25:24 +090010148 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010149
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010150 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +090010151 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010152 }
10153
10154 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +090010155 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +090010156 // The code is never supposed to add two reassignments of the same request. Make
10157 // sure this stays true, but without imposing this expensive check on all
10158 // reassignments on all user devices.
10159 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -080010160 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +090010161 throw new IllegalStateException("Trying to reassign ["
10162 + reassignment + "] but already have ["
10163 + existing + "]");
10164 }
10165 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +090010166 }
Chalard Jean46a62372019-12-10 21:25:24 +090010167 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010168 }
10169
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010170 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +090010171 // the passed request.
10172 @Nullable
10173 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010174 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010175 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010176 }
10177 return null;
10178 }
Chalard Jean49707572019-12-10 21:07:02 +090010179
10180 public String toString() {
10181 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
10182 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +090010183 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010184 for (final RequestReassignment rr : getRequestReassignments()) {
10185 sj.add(rr.toString());
10186 }
10187 return sj.toString();
10188 }
10189
10190 public String debugString() {
10191 final StringBuilder sb = new StringBuilder();
10192 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +090010193 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010194 for (final RequestReassignment rr : getRequestReassignments()) {
10195 sb.append("\n ").append(rr);
10196 }
10197 return sb.append("\n").toString();
10198 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010199 }
10200
Chalard Jean24344d72019-12-04 13:32:31 +090010201 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010202 @Nullable final NetworkRequest previousRequest,
10203 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +090010204 @Nullable final NetworkAgentInfo previousSatisfier,
10205 @Nullable final NetworkAgentInfo newSatisfier,
10206 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -080010207 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +090010208 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +090010209 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010210 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010211 log(" accepting network in place of " + previousSatisfier.toShortString()
10212 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010213 }
James Mattisa076c532020-12-02 14:12:41 -080010214 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010215 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +090010216 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +090010217 // If this network switch can't be supported gracefully, the request is not
10218 // lingered. This allows letting go of the network sooner to reclaim some
10219 // performance on the new network, since the radio can't do both at the same
10220 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010221 //
10222 // Also don't linger the request if the old network has been destroyed.
10223 // A destroyed network does not provide actual network connectivity, so
10224 // lingering it is not useful. In particular this ensures that a destroyed
10225 // network is outscored by its replacement,
10226 // then it is torn down immediately instead of being lingered, and any apps that
10227 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +090010228 previousSatisfier.lingerRequest(previousRequest.requestId, now);
10229 }
Chalard Jean24344d72019-12-04 13:32:31 +090010230 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010231 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010232 }
junyulai0ac374f2020-12-14 18:41:52 +080010233
10234 // To prevent constantly CPU wake up for nascent timer, if a network comes up
10235 // and immediately satisfies a request then remove the timer. This will happen for
10236 // all networks except in the case of an underlying network for a VCN.
10237 if (newSatisfier.isNascent()) {
10238 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +080010239 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010240 }
10241
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010242 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -080010243 newSatisfier.unlingerRequest(newRequest.requestId);
10244 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +080010245 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -080010246 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010247 }
Chalard Jeana8ac2302021-03-01 22:16:08 +090010248 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010249 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010250 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -080010251 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010252 }
James Mattisa076c532020-12-02 14:12:41 -080010253 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010254 }
James Mattisa076c532020-12-02 14:12:41 -080010255 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010256 }
10257
James Mattisa076c532020-12-02 14:12:41 -080010258 /**
10259 * This function is triggered when something can affect what network should satisfy what
10260 * request, and it computes the network reassignment from the passed collection of requests to
10261 * network match to the one that the system should now have. That data is encoded in an
10262 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
10263 * satisfier.
10264 *
10265 * After the reassignment is computed, it is applied to the state objects.
10266 *
10267 * @param networkRequests the nri objects to evaluate for possible network reassignment
10268 * @return NetworkReassignment listing of proposed network assignment changes
10269 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010270 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080010271 private NetworkReassignment computeNetworkReassignment(
10272 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010273 final NetworkReassignment changes = new NetworkReassignment();
10274
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010275 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010276 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010277 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010278 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010279 }
Chalard Jean857a1712019-12-10 21:08:07 +090010280
James Mattisa076c532020-12-02 14:12:41 -080010281 for (final NetworkRequestInfo nri : networkRequests) {
10282 // Non-multilayer listen requests can be ignored.
10283 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10284 continue;
10285 }
10286 NetworkAgentInfo bestNetwork = null;
10287 NetworkRequest bestRequest = null;
10288 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010289 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010290 // Stop evaluating as the highest possible priority request is satisfied.
10291 if (null != bestNetwork) {
10292 bestRequest = req;
10293 break;
10294 }
10295 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010296 if (null == bestNetwork && isDefaultBlocked(nri)) {
10297 // Remove default networking if disallowed for managed default requests.
10298 bestNetwork = mNoServiceNetwork;
10299 }
10300 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010301 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010302 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010303 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010304 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010305 }
10306 return changes;
10307 }
10308
James Mattisa076c532020-12-02 14:12:41 -080010309 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10310 return new HashSet<>(mNetworkRequests.values());
10311 }
10312
Paul Jensenc88b39b2015-06-16 14:27:36 -040010313 /**
James Mattisa076c532020-12-02 14:12:41 -080010314 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010315 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010316 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010317 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010318 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10319 }
10320
10321 /**
10322 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10323 * being disconnected.
10324 */
10325 private void rematchNetworksAndRequests(
10326 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10327 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010328 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010329 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010330 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010331 final long computed = SystemClock.elapsedRealtime();
10332 applyNetworkReassignment(changes, start);
10333 final long applied = SystemClock.elapsedRealtime();
10334 issueNetworkNeeds();
10335 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010336 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010337 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10338 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010339 log(changes.debugString());
10340 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010341 // Shorter form, only one line of log
10342 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10343 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010344 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010345 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010346
Chalard Jean1e4c2182023-10-06 18:45:53 +090010347 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10348 @Nullable final NetworkAgentInfo nai2) {
10349 if (null == nai1) return null == nai2;
10350 if (null == nai2) return false;
10351 return nai1.linkProperties.getInterfaceName()
10352 .equals(nai2.linkProperties.getInterfaceName());
10353 }
10354
Chalard Jeand7f762d2019-12-10 19:01:29 +090010355 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010356 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010357 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010358
10359 // Since most of the time there are only 0 or 1 background networks, it would probably
10360 // be more efficient to just use an ArrayList here. TODO : measure performance
10361 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10362 for (final NetworkAgentInfo nai : nais) {
10363 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10364 }
10365
Chalard Jeand7f762d2019-12-10 19:01:29 +090010366 // First, update the lists of satisfied requests in the network agents. This is necessary
10367 // because some code later depends on this state to be correct, most prominently computing
10368 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010369 for (final NetworkReassignment.RequestReassignment event :
10370 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010371 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10372 event.mOldNetworkRequest, event.mNewNetworkRequest,
10373 event.mOldNetwork, event.mNewNetwork,
10374 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010375 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010376
James Mattise3ef1912020-12-20 11:09:58 -080010377 // Process default network changes if applicable.
10378 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010379
Chalard Jean68eab722023-11-16 17:00:04 +090010380 // Update forwarding rules for the upstreams of local networks. Do this before sending
10381 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10382 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10383 // onAvailable so clients know what network the change is about. Store such changes in
10384 // an array that's only allocated if necessary (because it's almost never necessary).
10385 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10386 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10387 if (!nai.isLocalNetwork()) continue;
10388 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10389 if (null == nr) continue; // No upstream for this local network
10390 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10391 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10392 if (null == change) continue; // No change in upstreams for this network
10393 final String fromIface = nai.linkProperties.getInterfaceName();
10394 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10395 || change.mOldNetwork.isDestroyed()) {
10396 // There can be a change with the same interface name if the new network is the
10397 // replacement for the old network that was unregisteredAfterReplacement.
10398 try {
10399 if (null != change.mOldNetwork) {
10400 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10401 change.mOldNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010402 disableMulticastRouting(fromIface,
10403 change.mOldNetwork.linkProperties.getInterfaceName());
Chalard Jean68eab722023-11-16 17:00:04 +090010404 }
10405 // If the new upstream is already destroyed, there is no point in setting up
10406 // a forward (in fact, it might forward to the interface for some new network !)
10407 // Later when the upstream disconnects CS will try to remove the forward, which
10408 // is ignored with a benign log by RoutingCoordinatorService.
10409 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10410 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10411 change.mNewNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010412 applyMulticastRoutingConfig(fromIface,
10413 change.mNewNetwork.linkProperties.getInterfaceName(),
10414 nai.localNetworkConfig);
Chalard Jean68eab722023-11-16 17:00:04 +090010415 }
10416 } catch (final RemoteException e) {
10417 loge("Can't update forwarding rules", e);
10418 }
10419 }
10420 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10421 localInfoChangedAgents.add(nai);
10422 }
10423
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010424 // Notify requested networks are available after the default net is switched, but
10425 // before LegacyTypeTracker sends legacy broadcasts
10426 for (final NetworkReassignment.RequestReassignment event :
10427 changes.getRequestReassignments()) {
10428 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010429 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010430 } else {
James Mattisa076c532020-12-02 14:12:41 -080010431 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010432 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010433 }
10434 }
10435
junyulai0ac374f2020-12-14 18:41:52 +080010436 // Update the inactivity state before processing listen callbacks, because the background
10437 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010438 // just yet though, because they have to be sent after the listens are processed to keep
10439 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010440 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010441 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010442 // Rematching may have altered the inactivity state of some networks, so update all
10443 // inactivity timers. updateInactivityState reads the state from the network agent
10444 // and does nothing if the state has not changed : the source of truth is controlled
10445 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10446 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010447 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010448 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010449 }
10450 }
10451
Chalard Jeanb10ab412019-12-11 14:12:30 +090010452 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010453 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010454 // Process listen requests and update capabilities if the background state has
10455 // changed for this network. For consistency with previous behavior, send onLost
10456 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010457 processNewlyLostListenRequests(nai);
10458 if (oldBackground != nai.isBackgroundNetwork()) {
10459 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010460 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010461 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010462 }
10463
junyulai0ac374f2020-12-14 18:41:52 +080010464 for (final NetworkAgentInfo nai : inactiveNetworks) {
10465 // For nascent networks, if connecting with no foreground request, skip broadcasting
10466 // LOSING for backward compatibility. This is typical when mobile data connected while
10467 // wifi connected with mobile data always-on enabled.
10468 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010469 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010470 }
10471
Chalard Jean68eab722023-11-16 17:00:04 +090010472 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10473 if (null != localInfoChangedAgents) {
10474 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10475 notifyNetworkCallbacks(nai,
10476 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010477 }
10478 }
10479
James Mattise3ef1912020-12-20 11:09:58 -080010480 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010481
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010482 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010483 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010484 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010485 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010486 // This network has active linger timers and no requests, but is not
10487 // lingering. Linger it.
10488 //
10489 // One way (the only way?) this can happen if this network is unvalidated
10490 // and became unneeded due to another network improving its score to the
10491 // point where this network will no longer be able to satisfy any requests
10492 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010493 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010494 notifyNetworkLosing(nai, now);
10495 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010496 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010497 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010498 teardownUnneededNetwork(nai);
10499 }
10500 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010501 }
10502 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010503
Chalard Jean62edfd82019-12-02 18:39:29 +090010504 /**
10505 * Apply a change in background state resulting from rematching networks with requests.
10506 *
10507 * During rematch, a network may change background states by starting to satisfy or stopping
10508 * to satisfy a foreground request. Listens don't count for this. When a network changes
10509 * background states, its capabilities need to be updated and callbacks fired for the
10510 * capability change.
10511 *
10512 * @param nai The network that changed background states
10513 */
10514 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10515 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10516 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10517 updateNetworkPermissions(nai, newNc);
10518 nai.getAndSetNetworkCapabilities(newNc);
10519 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10520 }
10521
Chalard Jeanf0344532019-11-19 19:23:38 +090010522 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010523 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010524 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010525 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10526 changes.getReassignment(mDefaultRequest);
10527 final NetworkAgentInfo oldDefaultNetwork =
10528 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10529 final NetworkAgentInfo newDefaultNetwork =
10530 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010531
Chalard Jean5b409c72021-02-04 13:12:59 +090010532 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010533 // Maintain the illusion : since the legacy API only understands one network at a time,
10534 // if the default network changed, apps should see a disconnected broadcast for the
10535 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010536 if (oldDefaultNetwork != null) {
10537 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10538 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010539 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010540 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010541 // The new default network can be newly null if and only if the old default
10542 // network doesn't satisfy the default request any more because it lost a
10543 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010544 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010545 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010546 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010547 }
10548 }
10549
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010550 // Now that all the callbacks have been sent, send the legacy network broadcasts
10551 // as needed. This is necessary so that legacy requests correctly bind dns
10552 // requests to this network. The legacy users are listening for this broadcast
10553 // and will generally do a dns request so they can ensureRouteToHost and if
10554 // they do that before the callbacks happen they'll use the default network.
10555 //
10556 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10557 // callbacks, but if apps can receive the broadcast before the callback, they still might
10558 // have an inconsistent view of networking.
10559 //
10560 // This *does* introduce a race where if the user uses the new api
10561 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10562 // they may get old info. Reverse this after the old startUsing api is removed.
10563 // This is on top of the multiple intent sequencing referenced in the todo above.
10564 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010565 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010566 addNetworkToLegacyTypeTracker(nai);
10567 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010568 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010569 }
10570
Chalard Jean0354d8c2021-01-12 10:58:56 +090010571 private void issueNetworkNeeds() {
10572 ensureRunningOnConnectivityServiceThread();
10573 for (final NetworkOfferInfo noi : mNetworkOffers) {
10574 issueNetworkNeeds(noi);
10575 }
10576 }
10577
10578 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10579 ensureRunningOnConnectivityServiceThread();
10580 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10581 informOffer(nri, noi.offer, mNetworkRanker);
10582 }
10583 }
10584
10585 /**
10586 * Inform a NetworkOffer about any new situation of a request.
10587 *
10588 * This function handles updates to offers. A number of events may happen that require
10589 * updating the registrant for this offer about the situation :
10590 * • The offer itself was updated. This may lead the offer to no longer being able
10591 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10592 * or conversely being strengthened enough to beat the satisfier (and therefore
10593 * start being needed)
10594 * • The network satisfying a request changed (including cases where the request
10595 * starts or stops being satisfied). The new network may be a stronger or weaker
10596 * match than the old one, possibly affecting whether the offer is needed.
10597 * • The network satisfying a request updated their score. This may lead the offer
10598 * to no longer be able to beat it if the current satisfier got better, or
10599 * conversely start being a good choice if the current satisfier got weaker.
10600 *
10601 * @param nri The request
10602 * @param offer The offer. This may be an updated offer.
10603 */
10604 private static void informOffer(@NonNull NetworkRequestInfo nri,
10605 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10606 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10607 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010608
10609 // Multi-layer requests have a currently active request, the one being satisfied.
10610 // Since the system will try to bring up a better network than is currently satisfying
10611 // the request, NetworkProviders need to be told the offers matching the requests *above*
10612 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10613 // not needed, and the offer is needed for the active request iff the offer can beat
10614 // the satisfier.
10615 // For non-multilayer requests, the logic above gracefully degenerates to only the
10616 // last case.
10617 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10618 // providers that the offer is needed for this request, until the active request is found.
10619 // In a second phase, deal with the currently active request. In a third phase, inform
10620 // the providers that offer is unneeded for the remaining requests.
10621
10622 // First phase : inform providers of all requests above the active request.
10623 int i;
10624 for (i = 0; nri.mRequests.size() > i; ++i) {
10625 final NetworkRequest request = nri.mRequests.get(i);
10626 if (activeRequest == request) break; // Found the active request : go to phase 2
10627 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10628 // Since this request is higher-priority than the one currently satisfied, if the
10629 // offer can satisfy it, the provider should try and bring up the network for sure ;
10630 // no need to even ask the ranker – an offer that can satisfy is always better than
10631 // no network. Hence tell the provider so unless it already knew.
10632 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10633 offer.onNetworkNeeded(request);
10634 }
10635 }
10636
10637 // Second phase : deal with the active request (if any)
10638 if (null != activeRequest && activeRequest.isRequest()) {
10639 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010640 // If an offer can satisfy the request, it is considered needed if it is currently
10641 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010642 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010643 && satisfier.factorySerialNumber == offer.providerId
10644 && activeRequest.canBeSatisfiedBy(offer.caps);
10645 final boolean newNeeded = currentlyServing
10646 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010647 if (newNeeded != oldNeeded) {
10648 if (newNeeded) {
10649 offer.onNetworkNeeded(activeRequest);
10650 } else {
10651 // The offer used to be able to beat the satisfier. Now it can't.
10652 offer.onNetworkUnneeded(activeRequest);
10653 }
10654 }
10655 }
10656
10657 // Third phase : inform the providers that the offer isn't needed for any request
10658 // below the active one.
10659 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10660 final NetworkRequest request = nri.mRequests.get(i);
10661 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10662 // Since this request is lower-priority than the one currently satisfied, if the
10663 // offer can satisfy it, the provider should not try and bring up the network.
10664 // Hence tell the provider so unless it already knew.
10665 if (offer.neededFor(request)) {
10666 offer.onNetworkUnneeded(request);
10667 }
10668 }
10669 }
10670
Chalard Jean61c79252019-11-07 23:07:32 +090010671 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10672 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10673 NetworkRequest nr = nai.requestAt(i);
10674 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10675 // legacy type tracker filters out repeat adds
10676 mLegacyTypeTracker.add(nr.legacyType, nai);
10677 }
10678 }
10679
10680 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010681 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010682 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10683 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10684 if (nai.isVPN()) {
10685 mLegacyTypeTracker.add(TYPE_VPN, nai);
10686 }
10687 }
10688
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010689 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010690 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010691 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010692 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010693 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010694 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010695
Chalard Jean254bd162022-08-25 13:04:51 +090010696 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010697 // Don't repeat publish.
10698 if (newInetCondition == mDefaultInetConditionPublished) return;
10699
10700 mDefaultInetConditionPublished = newInetCondition;
10701 sendInetConditionBroadcast(nai.networkInfo);
10702 }
10703
Chalard Jeand61375d2020-01-14 22:46:36 +090010704 @NonNull
10705 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10706 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010707 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010708 final boolean suspended =
10709 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10710 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10711 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10712 // state. This is because the network could have been suspended before connecting,
10713 // or it could be disconnecting while being suspended, and in both these cases
10714 // the state should not be overridden. Note that the only detailed state that
10715 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10716 // worry about multiple different substates of CONNECTED.
10717 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10718 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010719 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10720 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10721 // network agent is created, then goes to suspended, then goes out of suspended without
10722 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010723 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010724 ? NetworkInfo.DetailedState.CONNECTED
10725 : NetworkInfo.DetailedState.CONNECTING,
10726 info.getReason(),
10727 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010728 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010729 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010730 return newInfo;
10731 }
10732
10733 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10734 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10735
Erik Kline99f301b2017-02-15 19:59:17 +090010736 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010737 NetworkInfo oldInfo = null;
10738 synchronized (networkAgent) {
10739 oldInfo = networkAgent.networkInfo;
10740 networkAgent.networkInfo = newInfo;
10741 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010742
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010743 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010744 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10745 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010746 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010747
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010748 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010749 // A network that has just connected has zero requests and is thus a foreground network.
10750 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10751
Luke Huangfdd11f82019-04-09 18:41:49 +080010752 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010753
10754 networkAgent.setCreated();
10755
10756 // If the network is created immediately on register, then apply the LinkProperties now.
10757 // Otherwise, this is done further down when the network goes into connected state.
10758 // Applying the LinkProperties means that the network is ready to carry traffic -
10759 // interfaces and routing rules have been added, DNS servers programmed, etc.
10760 // For VPNs, this must be done before the capabilities are updated, because as soon as
10761 // that happens, UIDs are routed to the network.
10762 if (shouldCreateNetworksImmediately()) {
10763 applyInitialLinkProperties(networkAgent);
10764 }
10765
10766 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10767 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010768 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010769 // Initialize the network's capabilities to their starting values according to the
10770 // underlying networks. This ensures that the capabilities are correct before
10771 // anything happens to the network.
10772 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010773 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010774 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010775 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010776 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010777 }
10778
Chalard Jean254bd162022-08-25 13:04:51 +090010779 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10780 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010781
lucaslin45e639b2019-04-03 17:09:28 +080010782 // NetworkCapabilities need to be set before sending the private DNS config to
10783 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010784 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10785
Erik Kline9a62f012018-03-21 07:18:33 -070010786 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010787 if (!shouldCreateNetworksImmediately()) {
10788 applyInitialLinkProperties(networkAgent);
10789 } else {
10790 // The network was created when the agent registered, and the LinkProperties are
10791 // already up-to-date. However, updateLinkProperties also makes some changes only
10792 // when the network connects. Apply those changes here. On T and below these are
10793 // handled by the applyInitialLinkProperties call just above.
10794 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10795 // If something depends on both LinkProperties and connected state, it should be in
10796 // this method as well.
10797 networkAgent.clatd.update();
10798 updateProxy(networkAgent.linkProperties, null);
10799 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010800
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010801 // If a rate limit has been configured and is applicable to this network (network
10802 // provides internet connectivity), apply it. The tc police filter cannot be attached
10803 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010804 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010805 // Note: in case of a system server crash, the NetworkController constructor in netd
10806 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10807 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10808 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10809 mIngressRateLimit);
10810 }
10811
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010812 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10813 // command must be sent after updating LinkProperties to maximize chances of
10814 // NetworkMonitor seeing the correct LinkProperties when starting.
10815 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010816 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010817 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010818 }
Chalard Jeand4900722022-02-06 12:25:38 +090010819 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10820 params.networkAgentConfig = networkAgent.networkAgentConfig;
10821 params.networkCapabilities = networkAgent.networkCapabilities;
10822 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10823 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010824 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10825 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10826 // call that would cause a Log.wtf to be emitted from the system_server process, and
10827 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10828 // process to check the interface version, just use an SDK check. NetworkStack will
10829 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010830 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010831 networkAgent.networkMonitor().notifyNetworkConnected(params);
10832 } else {
10833 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10834 params.networkCapabilities);
10835 }
Chalard Jean0f141332023-06-05 19:26:17 +090010836 final long evaluationDelay;
10837 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10838 // If the network is anything other than pure wifi, use the default timeout.
10839 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10840 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10841 // If the network is explicitly selected, use the default timeout because it's
10842 // shorter and the user is likely staring at the screen expecting it to validate
10843 // right away.
10844 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10845 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10846 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10847 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10848 } else {
10849 // It's wifi, automatically connected, and bad wifi is preferred : use the
10850 // longer timeout to avoid the device switching to captive portals with bad
10851 // signal or very slow response.
10852 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10853 }
10854 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010855
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010856 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10857 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10858 // capabilities, so it only needs to be done once on initial connect, not every time the
10859 // network's capabilities change. Note that we do this before rematching the network,
10860 // so we could decide to tear it down immediately afterwards. That's fine though - on
10861 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10862 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010863 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010864
junyulai0ac374f2020-12-14 18:41:52 +080010865 // Before first rematching networks, put an inactivity timer without any request, this
10866 // allows {@code updateInactivityState} to update the state accordingly and prevent
10867 // tearing down for any {@code unneeded} evaluation in this period.
10868 // Note that the timer will not be rescheduled since the expiry time is
10869 // fixed after connection regardless of the network satisfying other requests or not.
10870 // But it will be removed as soon as the network satisfies a request for the first time.
10871 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10872 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010873 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010874
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010875 if (mTrackMultiNetworkActivities) {
10876 // Start tracking activity of this network.
10877 // This must be called before rematchAllNetworksAndRequests since the network
10878 // should be tracked when the network becomes the default network.
10879 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10880 // can be triggered later if this network becomes the default network.
10881 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10882 }
10883
Paul Jensen05e85ee2014-09-11 11:00:39 -040010884 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010885 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010886
10887 // This has to happen after matching the requests, because callbacks are just requests.
10888 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010889 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010890 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010891 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010892 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010893 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010894 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010895 if (networkAgent.isVPN()) {
10896 // As the active or bound network changes for apps, broadcast the default proxy, as
10897 // apps may need to update their proxy data. This is called after disconnecting from
10898 // VPN to make sure we do not broadcast the old proxy data.
10899 // TODO(b/122649188): send the broadcast only to VPN users.
10900 mProxyTracker.sendProxyBroadcast();
10901 }
Chalard Jean254bd162022-08-25 13:04:51 +090010902 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10903 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010904 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010905 }
10906 }
10907
Chalard Jean28018572020-12-21 18:36:52 +090010908 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010909 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10910 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010911 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010912 }
10913
Erik Kline99f301b2017-02-15 19:59:17 +090010914 // Notify only this one new request of the current state. Transfer all the
10915 // current state by calling NetworkCapabilities and LinkProperties callbacks
10916 // so that callers can be guaranteed to have as close to atomicity in state
10917 // transfer as can be supported by this current API.
10918 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010919 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010920 if (nri.mPendingIntent != null) {
10921 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10922 // Attempt no subsequent state pushes where intents are involved.
10923 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010924 }
Erik Kline99f301b2017-02-15 19:59:17 +090010925
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010926 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010927 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010928 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10929 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10930 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010931 }
10932
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010933 // Notify the requests on this NAI that the network is now lingered.
10934 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010935 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010936 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10937 }
10938
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010939 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10940 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10941 return vpnBlocked
10942 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10943 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10944 }
10945
10946 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10947 if (blockedReasons == BLOCKED_REASON_NONE) {
10948 mUidBlockedReasons.delete(uid);
10949 } else {
10950 mUidBlockedReasons.put(uid, blockedReasons);
10951 }
10952 }
10953
junyulaif2c67e42018-08-07 19:50:45 +080010954 /**
10955 * Notify of the blocked state apps with a registered callback matching a given NAI.
10956 *
10957 * Unlike other callbacks, blocked status is different between each individual uid. So for
10958 * any given nai, all requests need to be considered according to the uid who filed it.
10959 *
10960 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010961 * @param oldMetered True if the previous network capabilities were metered.
10962 * @param newMetered True if the current network capabilities are metered.
10963 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10964 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010965 */
10966 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010967 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10968 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010969
10970 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10971 NetworkRequest nr = nai.requestAt(i);
10972 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010973
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010974 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10975 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10976 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010977 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010978 : oldVpnBlocked;
10979
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010980 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10981 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10982 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010983 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010984 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010985 }
10986 }
10987 }
10988
10989 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010990 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010991 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010992 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010993 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010994 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010995 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010996 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010997 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010998
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010999 final int oldBlockedState = getBlockedState(
11000 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
11001 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
11002 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080011003 continue;
junyulaif2c67e42018-08-07 19:50:45 +080011004 }
junyulaif2c67e42018-08-07 19:50:45 +080011005 for (int i = 0; i < nai.numNetworkRequests(); i++) {
11006 NetworkRequest nr = nai.requestAt(i);
11007 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011008 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011009 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
11010 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080011011 }
11012 }
11013 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011014 }
11015
Chalard Jean3a3f5f22019-04-10 23:07:55 +090011016 @VisibleForTesting
11017 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090011018 // The NetworkInfo we actually send out has no bearing on the real
11019 // state of affairs. For example, if the default connection is mobile,
11020 // and a request for HIPRI has just gone away, we need to pretend that
11021 // HIPRI has just disconnected. So we need to set the type to HIPRI and
11022 // the state to DISCONNECTED, even though the network is of type MOBILE
11023 // and is still connected.
11024 NetworkInfo info = new NetworkInfo(nai.networkInfo);
11025 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090011026 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070011027 if (state != DetailedState.DISCONNECTED) {
11028 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090011029 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011030 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070011031 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070011032 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
11033 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
11034 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
11035 if (info.isFailover()) {
11036 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
11037 nai.networkInfo.setFailover(false);
11038 }
11039 if (info.getReason() != null) {
11040 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
11041 }
11042 if (info.getExtraInfo() != null) {
11043 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
11044 }
11045 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090011046 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080011047 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070011048 if (newDefaultAgent != null) {
11049 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
11050 newDefaultAgent.networkInfo);
11051 } else {
11052 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
11053 }
11054 }
11055 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
11056 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090011057 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011058 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090011059 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011060 }
11061 }
11062 }
11063
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011064 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090011065 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090011066 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090011067 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090011068 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090011069 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
11070 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011071 NetworkRequestInfo nri = mNetworkRequests.get(nr);
11072 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011073 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011074 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011075 } else {
11076 sendPendingIntentForRequest(nri, networkAgent, notifyType);
11077 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011078 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011079 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070011080
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011081 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
11082 notifyNetworkCallbacks(networkAgent, notifyType, 0);
11083 }
11084
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011085 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090011086 * Returns the list of all interfaces that could be used by network traffic that does not
11087 * explicitly specify a network. This includes the default network, but also all VPNs that are
11088 * currently connected.
11089 *
11090 * Must be called on the handler thread.
11091 */
junyulaie7c7d2a2021-01-26 15:29:15 +080011092 @NonNull
11093 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080011094 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080011095 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080011096 final Set<Integer> activeNetIds = new ArraySet<>();
11097 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
11098 if (nri.isBeingSatisfied()) {
11099 activeNetIds.add(nri.getSatisfier().network().netId);
11100 }
11101 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090011102 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090011103 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090011104 defaultNetworks.add(nai.network);
11105 }
11106 }
junyulaie7c7d2a2021-01-26 15:29:15 +080011107 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090011108 }
11109
11110 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090011111 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
11112 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011113 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080011114 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080011115 ensureRunningOnConnectivityServiceThread();
11116 String activeIface = null;
11117 LinkProperties activeLinkProperties = getActiveLinkProperties();
11118 if (activeLinkProperties != null) {
11119 activeIface = activeLinkProperties.getInterfaceName();
11120 }
Benedict Wong9308cd32019-06-12 17:46:31 +000011121
junyulai2050bed2021-01-23 09:46:34 +080011122 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011123 try {
junyulaide41fc22021-01-22 22:46:01 +080011124 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090011125 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080011126 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
11127 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011128 } catch (Exception ignored) {
11129 }
11130 }
11131
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070011132 @Override
Udam Sainicd645462016-01-04 12:16:14 -080011133 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080011134 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090011135 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090011136 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011137
11138 if (!TextUtils.isEmpty(settingUrl)) {
11139 return settingUrl;
11140 }
11141
11142 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011143 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011144 if (!TextUtils.isEmpty(settingUrl)) {
11145 return settingUrl;
11146 }
11147
11148 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080011149 }
11150
11151 @Override
junyulai070f9ff2019-01-16 20:23:34 +080011152 public void startNattKeepalive(Network network, int intervalSeconds,
11153 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011154 enforceKeepalivePermission();
11155 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080011156 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000011157 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
11158 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000011159 // false and set the underpinned network to null because there is no way and no
11160 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
11161 // deprecated method.
11162 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011163 }
11164
11165 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011166 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080011167 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000011168 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070011169 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080011170 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011171 mKeepaliveTracker.startNattKeepalive(
11172 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000011173 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
11174 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070011175 } finally {
11176 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11177 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011178 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11179 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011180 }
11181 }
junyulaid05a1922019-01-15 11:32:44 +080011182 }
11183
11184 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011185 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080011186 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070011187 try {
11188 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080011189 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011190 mKeepaliveTracker.startTcpKeepalive(
11191 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
11192 } finally {
11193 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11194 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011195 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11196 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011197 }
11198 }
junyulai0835a1e2019-01-08 20:04:33 +080011199 }
11200
11201 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011202 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011203 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011204 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
11205 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011206 }
11207
11208 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090011209 public int[] getSupportedKeepalives() {
11210 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
11211 // Backwards compatibility with CTS 13
11212 android.Manifest.permission.QUERY_ALL_PACKAGES);
11213
11214 return BinderUtils.withCleanCallingIdentity(() ->
11215 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
11216 }
11217
11218 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070011219 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080011220 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070011221
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011222 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080011223 final long token = Binder.clearCallingIdentity();
11224 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011225 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
11226 UserHandle.getUserHandleForUid(uid))) {
11227 return;
11228 }
11229
Heemin Seogdb8489d2019-06-12 09:21:44 -070011230 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
11231 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011232
11233 // Turn airplane mode off
11234 setAirplaneMode(false);
11235
11236 // restore private DNS settings to default mode (opportunistic)
11237 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
11238 UserHandle.getUserHandleForUid(uid))) {
11239 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
11240 PRIVATE_DNS_MODE_OPPORTUNISTIC);
11241 }
11242
11243 Settings.Global.putString(mContext.getContentResolver(),
11244 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080011245 } finally {
11246 Binder.restoreCallingIdentity(token);
11247 }
Stuart Scottd5463642015-04-02 18:00:02 -070011248 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040011249
Ricky Wai7097cc92018-01-23 04:09:45 +000011250 @Override
11251 public byte[] getNetworkWatchlistConfigHash() {
11252 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
11253 if (nwm == null) {
11254 loge("Unable to get NetworkWatchlistManager");
11255 return null;
11256 }
11257 // Redirect it to network watchlist service to access watchlist file and calculate hash.
11258 return nwm.getWatchlistConfigHash();
11259 }
11260
Hugo Benichibe0c7652016-05-31 16:28:06 +090011261 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090011262 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080011263 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090011264 }
Hugo Benichif4210292017-04-21 15:07:12 +090011265
11266 private static boolean toBool(int encodedBoolean) {
11267 return encodedBoolean != 0; // Only 0 means false.
11268 }
11269
11270 private static int encodeBool(boolean b) {
11271 return b ? 1 : 0;
11272 }
mswest4632928412018-03-12 10:34:34 -070011273
11274 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011275 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
11276 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
11277 @NonNull String[] args) {
11278 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11279 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011280 }
11281
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011282 private class ShellCmd extends BasicShellCommandHandler {
Suprabh Shukla22ea1662024-02-08 16:06:01 -080011283
11284 private Boolean parseBooleanArgument(final String arg) {
11285 if ("true".equals(arg)) {
11286 return true;
11287 } else if ("false".equals(arg)) {
11288 return false;
11289 } else {
11290 getOutPrintWriter().println("Invalid boolean argument: " + arg);
11291 return null;
11292 }
11293 }
11294
11295 private Integer parseIntegerArgument(final String arg) {
11296 try {
11297 return Integer.valueOf(arg);
11298 } catch (NumberFormatException ne) {
11299 getOutPrintWriter().println("Invalid integer argument: " + arg);
11300 return null;
11301 }
11302 }
11303
mswest4632928412018-03-12 10:34:34 -070011304 @Override
11305 public int onCommand(String cmd) {
11306 if (cmd == null) {
11307 return handleDefaultCommands(cmd);
11308 }
11309 final PrintWriter pw = getOutPrintWriter();
11310 try {
11311 switch (cmd) {
11312 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011313 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11314 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011315 final String action = getNextArg();
11316 if ("enable".equals(action)) {
11317 setAirplaneMode(true);
11318 return 0;
11319 } else if ("disable".equals(action)) {
11320 setAirplaneMode(false);
11321 return 0;
11322 } else if (action == null) {
11323 final ContentResolver cr = mContext.getContentResolver();
11324 final int enabled = Settings.Global.getInt(cr,
11325 Settings.Global.AIRPLANE_MODE_ON);
11326 pw.println(enabled == 0 ? "disabled" : "enabled");
11327 return 0;
11328 } else {
11329 onHelp();
11330 return -1;
11331 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011332 case "set-chain3-enabled": {
11333 final Boolean enabled = parseBooleanArgument(getNextArg());
11334 if (null == enabled) {
11335 onHelp();
11336 return -1;
11337 }
11338 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11339 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11340 enabled);
11341 return 0;
11342 }
11343 case "get-chain3-enabled": {
11344 final boolean chainEnabled = getFirewallChainEnabled(
11345 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11346 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11347 return 0;
11348 }
11349 case "set-package-networking-enabled": {
11350 final Boolean enabled = parseBooleanArgument(getNextArg());
11351 final String packageName = getNextArg();
11352 if (null == enabled || null == packageName) {
11353 onHelp();
11354 return -1;
11355 }
11356 // Throws NameNotFound if the package doesn't exist.
11357 final int appId = setPackageFirewallRule(
11358 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11359 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11360 final String msg = (enabled ? "Enabled" : "Disabled")
11361 + " networking for " + packageName + ", appId " + appId;
11362 Log.i(TAG, msg);
11363 pw.println(msg);
11364 return 0;
11365 }
11366 case "get-package-networking-enabled": {
11367 final String packageName = getNextArg();
11368 final int rule = getPackageFirewallRule(
11369 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11370 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11371 pw.println(packageName + ":" + "allow");
11372 } else if (FIREWALL_RULE_DENY == rule) {
11373 pw.println(packageName + ":" + "deny");
11374 } else {
11375 throw new IllegalStateException("Unknown rule " + rule + " for package "
11376 + packageName);
11377 }
11378 return 0;
11379 }
Suprabh Shukla22ea1662024-02-08 16:06:01 -080011380 case "set-background-networking-enabled-for-uid": {
11381 final Integer uid = parseIntegerArgument(getNextArg());
11382 final Boolean enabled = parseBooleanArgument(getNextArg());
11383 if (null == enabled || null == uid) {
11384 onHelp();
11385 return -1;
11386 }
11387 final int rule = enabled ? FIREWALL_RULE_ALLOW : FIREWALL_RULE_DEFAULT;
11388 setUidFirewallRule(FIREWALL_CHAIN_BACKGROUND, uid, rule);
11389 final String msg = (enabled ? "Enabled" : "Disabled")
11390 + " background networking for uid " + uid;
11391 Log.i(TAG, msg);
11392 pw.println(msg);
11393 return 0;
11394 }
11395 case "get-background-networking-enabled-for-uid": {
11396 final Integer uid = parseIntegerArgument(getNextArg());
11397 if (null == uid) {
11398 onHelp();
11399 return -1;
11400 }
11401 final int rule = getUidFirewallRule(FIREWALL_CHAIN_BACKGROUND, uid);
11402 if (FIREWALL_RULE_ALLOW == rule) {
11403 pw.println(uid + ": allow");
11404 } else if (FIREWALL_RULE_DENY == rule || FIREWALL_RULE_DEFAULT == rule) {
11405 pw.println(uid + ": deny");
11406 } else {
11407 throw new IllegalStateException(
11408 "Unknown rule " + rule + " for uid " + uid);
11409 }
11410 return 0;
11411 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011412 case "reevaluate":
11413 // Usage : adb shell cmd connectivity reevaluate <netId>
11414 // If netId is omitted, then reevaluate the default network
11415 final String netId = getNextArg();
11416 final NetworkAgentInfo nai;
11417 if (null == netId) {
11418 // Note that the command is running on the wrong thread to call this,
11419 // so this could in principle return stale data. But it can't crash.
11420 nai = getDefaultNetwork();
11421 } else {
11422 // If netId can't be parsed, this throws NumberFormatException, which
11423 // is passed back to adb who prints it.
11424 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11425 }
11426 if (null == nai) {
11427 pw.println("Unknown network (net ID not found or no default network)");
11428 return 0;
11429 }
11430 Log.d(TAG, "Reevaluating network " + nai.network);
11431 reportNetworkConnectivity(nai.network, !nai.isValidated());
11432 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011433 case "bpf-get-cgroup-program-id": {
11434 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11435 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11436 // for more detail.
11437 // If type can't be parsed, this throws NumberFormatException, which
11438 // is passed back to adb who prints it.
11439 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011440 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011441 pw.println(ret);
11442 return 0;
11443 }
mswest4632928412018-03-12 10:34:34 -070011444 default:
11445 return handleDefaultCommands(cmd);
11446 }
11447 } catch (Exception e) {
11448 pw.println(e);
11449 }
11450 return -1;
11451 }
11452
11453 @Override
11454 public void onHelp() {
11455 PrintWriter pw = getOutPrintWriter();
11456 pw.println("Connectivity service commands:");
11457 pw.println(" help");
11458 pw.println(" Print this help text.");
11459 pw.println(" airplane-mode [enable|disable]");
11460 pw.println(" Turn airplane mode on or off.");
11461 pw.println(" airplane-mode");
11462 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011463 pw.println(" set-chain3-enabled [true|false]");
11464 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11465 pw.println(" get-chain3-enabled");
11466 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11467 pw.println(" set-package-networking-enabled [true|false] [package name]");
11468 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11469 + " no effect if the chain is disabled.");
11470 pw.println(" get-package-networking-enabled [package name]");
11471 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
Suprabh Shukla22ea1662024-02-08 16:06:01 -080011472 pw.println(" set-background-networking-enabled-for-uid [uid] [true|false]");
11473 pw.println(" Set the allow bit in FIREWALL_CHAIN_BACKGROUND for the given uid.");
11474 pw.println(" get-background-networking-enabled-for-uid [uid]");
11475 pw.println(" Get the allow bit in FIREWALL_CHAIN_BACKGROUND for the given uid.");
mswest4632928412018-03-12 10:34:34 -070011476 }
11477 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011478
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011479 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011480 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11481 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11482 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011483 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011484 }
11485
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011486 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11487 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011488 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11489 final TransportInfo newInfo = nc.getTransportInfo();
11490 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11491 return;
11492 }
11493 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011494 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011495 }
11496 }
11497
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011498 /**
11499 * @param connectionInfo the connection to resolve.
11500 * @return {@code uid} if the connection is found and the app has permission to observe it
11501 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11502 * connection is not found.
11503 */
11504 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011505 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11506 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11507 }
11508
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011509 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011510 connectionInfo.local, connectionInfo.remote);
11511
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011512 if (uid == INVALID_UID) return uid; // Not found.
11513
11514 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11515 // VPN, if any, that applies to the UID that owns the connection.
Junyu Lai71b51532024-02-01 10:39:01 +080011516 if (hasNetworkStackPermission()) return uid;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011517
11518 final NetworkAgentInfo vpn = getVpnForUid(uid);
11519 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011520 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011521 return INVALID_UID;
11522 }
11523
11524 return uid;
11525 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011526
Benedict Wong493e04b2018-11-09 14:45:34 -080011527 /**
11528 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11529 *
11530 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11531 */
11532 @Override
11533 public IBinder startOrGetTestNetworkService() {
11534 synchronized (mTNSLock) {
11535 TestNetworkService.enforceTestNetworkPermissions(mContext);
11536
11537 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011538 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011539 }
11540
11541 return mTNS;
11542 }
11543 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011544
Cody Kesting73708bf2019-12-18 10:57:50 -080011545 /**
11546 * Handler used for managing all Connectivity Diagnostics related functions.
11547 *
11548 * @see android.net.ConnectivityDiagnosticsManager
11549 *
11550 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11551 */
11552 @VisibleForTesting
11553 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011554 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11555
Cody Kesting73708bf2019-12-18 10:57:50 -080011556 /**
11557 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11558 * android.net.ConnectivityDiagnosticsManager}.
11559 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11560 * NetworkRequestInfo to be registered
11561 */
11562 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11563
11564 /**
11565 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11566 * android.net.ConnectivityDiagnosticsManager}.
11567 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11568 * arg1 = the uid of the caller
11569 */
11570 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11571
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011572 /**
11573 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011574 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011575 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11576 * NetworkMonitor.
11577 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011578 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011579 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011580
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011581 /**
11582 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11583 * been detected on the network.
11584 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11585 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11586 * arg2 = NetID.
11587 * data = PersistableBundle of extras passed from NetworkMonitor.
11588 */
11589 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11590
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011591 /**
11592 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11593 * the platform. This event will invoke {@link
11594 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11595 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011596 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011597 */
11598 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11599
Cody Kesting73708bf2019-12-18 10:57:50 -080011600 private ConnectivityDiagnosticsHandler(Looper looper) {
11601 super(looper);
11602 }
11603
11604 @Override
11605 public void handleMessage(Message msg) {
11606 switch (msg.what) {
11607 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11608 handleRegisterConnectivityDiagnosticsCallback(
11609 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11610 break;
11611 }
11612 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11613 handleUnregisterConnectivityDiagnosticsCallback(
11614 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11615 break;
11616 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011617 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011618 final ConnectivityReportEvent reportEvent =
11619 (ConnectivityReportEvent) msg.obj;
11620
Aaron Huang959d3642021-01-21 15:47:41 +080011621 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011622 break;
11623 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011624 case EVENT_DATA_STALL_SUSPECTED: {
11625 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011626 final Pair<Long, PersistableBundle> arg =
11627 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011628 if (nai == null) break;
11629
Aaron Huang959d3642021-01-21 15:47:41 +080011630 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011631 break;
11632 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011633 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011634 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011635 break;
11636 }
11637 default: {
11638 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11639 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011640 }
11641 }
11642 }
11643
11644 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11645 @VisibleForTesting
11646 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11647 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11648 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011649 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011650
11651 @VisibleForTesting
11652 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011653 @NonNull IConnectivityDiagnosticsCallback cb,
11654 @NonNull NetworkRequestInfo nri,
11655 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011656 mCb = cb;
11657 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011658 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011659 }
11660
11661 @Override
11662 public void binderDied() {
11663 log("ConnectivityDiagnosticsCallback IBinder died.");
11664 unregisterConnectivityDiagnosticsCallback(mCb);
11665 }
11666 }
11667
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011668 /**
11669 * Class used for sending information from {@link
11670 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11671 */
11672 private static class NetworkTestedResults {
11673 private final int mNetId;
11674 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011675 @Nullable private final String mRedirectUrl;
11676
11677 private NetworkTestedResults(
11678 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11679 mNetId = netId;
11680 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011681 mRedirectUrl = redirectUrl;
11682 }
11683 }
11684
11685 /**
11686 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11687 * ConnectivityDiagnosticsHandler}.
11688 */
11689 private static class ConnectivityReportEvent {
11690 private final long mTimestampMillis;
11691 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011692 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011693
Aaron Huang959d3642021-01-21 15:47:41 +080011694 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11695 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011696 mTimestampMillis = timestampMillis;
11697 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011698 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011699 }
11700 }
11701
Cody Kestingf1120be2020-08-03 18:01:40 -070011702 /**
11703 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11704 * ConnectivityDiagnosticsHandler}.
11705 */
11706 private static class ReportedNetworkConnectivityInfo {
11707 public final boolean hasConnectivity;
11708 public final boolean isNetworkRevalidating;
11709 public final int reporterUid;
11710 @NonNull public final NetworkAgentInfo nai;
11711
11712 private ReportedNetworkConnectivityInfo(
11713 boolean hasConnectivity,
11714 boolean isNetworkRevalidating,
11715 int reporterUid,
11716 @NonNull NetworkAgentInfo nai) {
11717 this.hasConnectivity = hasConnectivity;
11718 this.isNetworkRevalidating = isNetworkRevalidating;
11719 this.reporterUid = reporterUid;
11720 this.nai = nai;
11721 }
11722 }
11723
Cody Kesting73708bf2019-12-18 10:57:50 -080011724 private void handleRegisterConnectivityDiagnosticsCallback(
11725 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11726 ensureRunningOnConnectivityServiceThread();
11727
11728 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011729 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011730 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11731
James Mattis64b8b0f2020-11-24 17:40:49 -080011732 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11733 // confusing for these networks to change when an NRI is satisfied in another layer.
11734 if (nri.isMultilayerRequest()) {
11735 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11736 + "network requests.");
11737 }
11738
Cody Kesting73708bf2019-12-18 10:57:50 -080011739 // This means that the client registered the same callback multiple times. Do
11740 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011741 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011742 if (VDBG) log("Diagnostics callback is already registered");
11743
11744 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11745 // incremented when the NetworkRequestInfo is created as part of
11746 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011747 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011748 return;
11749 }
11750
Cody Kesting31f1ff62020-03-05 10:46:02 -080011751 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011752
11753 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011754 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011755 } catch (RemoteException e) {
11756 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011757 return;
11758 }
11759
11760 // Once registered, provide ConnectivityReports for matching Networks
11761 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11762 synchronized (mNetworkForNetId) {
11763 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11764 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011765 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11766 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011767 matchingNetworks.add(nai);
11768 }
11769 }
11770 }
11771 for (final NetworkAgentInfo nai : matchingNetworks) {
11772 final ConnectivityReport report = nai.getConnectivityReport();
11773 if (report == null) {
11774 continue;
11775 }
Junyu Lai71b51532024-02-01 10:39:01 +080011776 if (!hasConnectivityDiagnosticsPermissions(
Cody Kestingb77bf702020-02-12 14:50:58 -080011777 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11778 continue;
11779 }
11780
11781 try {
11782 cb.onConnectivityReportAvailable(report);
11783 } catch (RemoteException e) {
11784 // Exception while sending the ConnectivityReport. Move on to the next network.
11785 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011786 }
11787 }
11788
11789 private void handleUnregisterConnectivityDiagnosticsCallback(
11790 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11791 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011792 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011793
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011794 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11795 mConnectivityDiagnosticsCallbacks.remove(iCb);
11796 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011797 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11798 return;
11799 }
11800
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011801 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011802
Cody Kesting70fa2b22020-12-02 12:16:56 -080011803 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11804 // (if the Binder died)
11805 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11806 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011807 return;
11808 }
11809
Cody Kesting46cb1672020-03-04 13:35:20 -080011810 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11811 // incremented when the NetworkRequestInfo is created as part of
11812 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011813 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011814
Cody Kesting31f1ff62020-03-05 10:46:02 -080011815 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011816 }
11817
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011818 private void handleNetworkTestedWithExtras(
11819 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11820 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011821 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011822 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011823 final ConnectivityReport report =
11824 new ConnectivityReport(
11825 reportEvent.mNai.network,
11826 reportEvent.mTimestampMillis,
11827 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011828 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011829 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011830 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011831
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011832 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011833 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011834 for (final IConnectivityDiagnosticsCallback cb : results) {
11835 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011836 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011837 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011838 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011839 }
11840 }
11841 }
11842
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011843 private void handleDataStallSuspected(
11844 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11845 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011846 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011847 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011848 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011849 new DataStallReport(
11850 nai.network,
11851 timestampMillis,
11852 detectionMethod,
11853 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011854 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011855 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011856 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011857 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011858 for (final IConnectivityDiagnosticsCallback cb : results) {
11859 try {
11860 cb.onDataStallSuspected(report);
11861 } catch (RemoteException ex) {
11862 loge("Error invoking onDataStallSuspected", ex);
11863 }
11864 }
11865 }
11866
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011867 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011868 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11869 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11870 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11871
11872 // If the Network is being re-validated as a result of this call to
11873 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11874 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011875 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011876 getMatchingPermissionedCallbacks(
11877 nai,
11878 reportedNetworkConnectivityInfo.isNetworkRevalidating
11879 ? Process.INVALID_UID
11880 : reportedNetworkConnectivityInfo.reporterUid);
11881
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011882 for (final IConnectivityDiagnosticsCallback cb : results) {
11883 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011884 cb.onNetworkConnectivityReported(
11885 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011886 } catch (RemoteException ex) {
11887 loge("Error invoking onNetworkConnectivityReported", ex);
11888 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011889
11890 // If the Network isn't re-validating, also provide the cached report. If there is no
11891 // cached report, the Network is still being validated and a report will be sent once
11892 // validation is complete. Note that networks which never undergo validation will still
11893 // have a cached ConnectivityReport with RESULT_SKIPPED.
11894 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11895 try {
11896 cb.onConnectivityReportAvailable(cachedReport);
11897 } catch (RemoteException ex) {
11898 loge("Error invoking onConnectivityReportAvailable", ex);
11899 }
11900 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011901 }
11902 }
11903
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011904 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011905 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11906 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011907 sanitized.setUids(null);
11908 sanitized.setAdministratorUids(new int[0]);
11909 sanitized.setOwnerUid(Process.INVALID_UID);
11910 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011911 }
11912
Cody Kestingf1120be2020-08-03 18:01:40 -070011913 /**
11914 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11915 *
11916 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11917 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011918 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011919 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011920 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011921 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011922 mConnectivityDiagnosticsCallbacks.entrySet()) {
11923 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11924 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011925
James Mattis64b8b0f2020-11-24 17:40:49 -080011926 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011927 if (!nai.satisfies(nri.mRequests.get(0))) {
11928 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011929 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011930
11931 // UID for this callback must either be:
11932 // - INVALID_UID (which sends callbacks to all UIDs), or
11933 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11934 // notified as a result)
11935 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11936 continue;
11937 }
11938
Junyu Lai71b51532024-02-01 10:39:01 +080011939 if (!hasConnectivityDiagnosticsPermissions(
Cody Kestingf1120be2020-08-03 18:01:40 -070011940 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11941 continue;
11942 }
11943
11944 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011945 }
11946 return results;
11947 }
11948
Cody Kesting7474f672021-05-11 14:22:40 -070011949 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11950 @NonNull NetworkAgentInfo nai) {
11951 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11952 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11953 }
11954
Cody Kesting160ef392021-05-05 13:17:22 -070011955 private boolean hasLocationPermission(String packageName, int uid) {
11956 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11957 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11958 // call in a try-catch.
11959 try {
11960 if (!mLocationPermissionChecker.checkLocationPermission(
11961 packageName, null /* featureId */, uid, null /* message */)) {
11962 return false;
11963 }
11964 } catch (SecurityException e) {
11965 return false;
11966 }
11967
11968 return true;
11969 }
11970
11971 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11972 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011973 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011974 && virtual.networkCapabilities.getOwnerUid() == uid
11975 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11976 return true;
11977 }
11978 }
11979
11980 return false;
11981 }
11982
Junyu Lai71b51532024-02-01 10:39:01 +080011983 @CheckResult
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011984 @VisibleForTesting
Junyu Lai71b51532024-02-01 10:39:01 +080011985 boolean hasConnectivityDiagnosticsPermissions(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011986 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
Junyu Lai71b51532024-02-01 10:39:01 +080011987 if (hasNetworkStackPermission(callbackPid, callbackUid)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011988 return true;
11989 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011990 if (mAllowSysUiConnectivityReports
Junyu Lai71b51532024-02-01 10:39:01 +080011991 && hasSystemBarServicePermission(callbackPid, callbackUid)) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011992 return true;
11993 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011994
Cody Kesting160ef392021-05-05 13:17:22 -070011995 // Administrator UIDs also contains the Owner UID
11996 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11997 if (!CollectionUtils.contains(administratorUids, callbackUid)
11998 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011999 return false;
12000 }
12001
Cody Kesting7474f672021-05-11 14:22:40 -070012002 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
12003 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012004 }
12005
Cody Kestingd199a9d2019-12-17 12:55:28 -080012006 @Override
12007 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012008 @NonNull IConnectivityDiagnosticsCallback callback,
12009 @NonNull NetworkRequest request,
12010 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070012011 Objects.requireNonNull(callback, "callback must not be null");
12012 Objects.requireNonNull(request, "request must not be null");
12013 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
12014
Cody Kesting73708bf2019-12-18 10:57:50 -080012015 if (request.legacyType != TYPE_NONE) {
12016 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
12017 + " Please use NetworkCapabilities instead.");
12018 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090012019 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080012020 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080012021
12022 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
12023 // and administrator uids to be safe.
12024 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080012025 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080012026
12027 final NetworkRequest requestWithId =
12028 new NetworkRequest(
12029 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
12030
12031 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
12032 //
12033 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
12034 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
12035 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090012036 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080012037 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080012038 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080012039
12040 mConnectivityDiagnosticsHandler.sendMessage(
12041 mConnectivityDiagnosticsHandler.obtainMessage(
12042 ConnectivityDiagnosticsHandler
12043 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
12044 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080012045 }
12046
12047 @Override
12048 public void unregisterConnectivityDiagnosticsCallback(
12049 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012050 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080012051 mConnectivityDiagnosticsHandler.sendMessage(
12052 mConnectivityDiagnosticsHandler.obtainMessage(
12053 ConnectivityDiagnosticsHandler
12054 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090012055 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080012056 0,
12057 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080012058 }
Cody Kestingf53a0752020-04-15 12:33:28 -070012059
Yan Yanfe96dde2022-12-05 23:00:01 +000012060 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
12061 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
12062 if (underlyingNetworks == null) return false;
12063
12064 for (Network network : underlyingNetworks) {
12065 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
12066 return true;
12067 }
12068 }
12069 return false;
12070 }
12071
Cody Kestingf53a0752020-04-15 12:33:28 -070012072 @Override
12073 public void simulateDataStall(int detectionMethod, long timestampMillis,
12074 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070012075 Objects.requireNonNull(network, "network must not be null");
12076 Objects.requireNonNull(extras, "extras must not be null");
12077
paulhu3ffffe72021-09-16 10:15:22 +080012078 enforceAnyPermissionOf(mContext,
12079 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070012080 android.Manifest.permission.NETWORK_STACK);
12081 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000012082 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
12083 throw new SecurityException(
12084 "Data Stall simulation is only possible for test networks or networks built on"
12085 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070012086 }
12087
12088 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000012089 if (nai == null
12090 || (nai.creatorUid != mDeps.getCallingUid()
12091 && nai.creatorUid != Process.SYSTEM_UID)) {
12092 throw new SecurityException(
12093 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070012094 }
12095
Cody Kesting652e3ec2020-05-21 12:08:21 -070012096 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
12097 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
12098 // Data Stall information as a DataStallReportParcelable and passing to
12099 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
12100 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070012101 final DataStallReportParcelable p = new DataStallReportParcelable();
12102 p.timestampMillis = timestampMillis;
12103 p.detectionMethod = detectionMethod;
12104
12105 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
12106 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
12107 }
12108 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
12109 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
12110 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
12111 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
12112 }
12113
Serik Beketayevec8ad212020-12-07 22:43:07 -080012114 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070012115 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012116
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012117 /**
12118 * Class to hold the information for network activity change event from idle timers
12119 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
12120 */
12121 private static final class NetworkActivityParams {
12122 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012123 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
12124 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012125 public final int label;
12126 public final long timestampNs;
12127 // Uid represents the uid that was responsible for waking the radio.
12128 // -1 for no uid and uid is -1 if isActive is false.
12129 public final int uid;
12130
12131 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
12132 this.isActive = isActive;
12133 this.label = label;
12134 this.timestampNs = timestampNs;
12135 this.uid = uid;
12136 }
12137 }
12138
lucaslin66f44212021-02-23 01:12:55 +080012139 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
12140 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012141 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080012142 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012143 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
12144 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080012145 }
lucaslin37a16d92021-01-21 19:48:09 +080012146
12147 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090012148 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012149 mHandler.post(() -> {
12150 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090012151 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012152 }
12153 });
lucaslin37a16d92021-01-21 19:48:09 +080012154 }
12155
12156 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090012157 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012158 mHandler.post(() -> {
12159 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090012160 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012161 }
12162 });
lucaslin66f44212021-02-23 01:12:55 +080012163 }
12164 }
12165
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012166 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080012167 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
12168
12169 /**
12170 * Class used for updating network activity tracking with netd and notify network activity
12171 * changes.
12172 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012173 @VisibleForTesting
12174 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080012175 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080012176 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080012177 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012178 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080012179 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
12180 new RemoteCallbackList<>();
12181 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012182 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012183 // If there is no default network, default network is considered active to keep the existing
12184 // behavior. Initial value is used until first connect to the default network.
12185 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012186 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012187 // Key is netId. Value is configured idle timer information.
12188 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012189 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012190 // Store netIds of Wi-Fi networks whose idletimers report that they are active
12191 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
12192 // Store netIds of cellular networks whose idletimers report that they are active
12193 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080012194
Chalard Jean46bfbf02022-02-02 00:56:25 +090012195 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080012196 public final int timeout;
12197 public final int transportType;
12198
12199 IdleTimerParams(int timeout, int transport) {
12200 this.timeout = timeout;
12201 this.transportType = transport;
12202 }
12203 }
12204
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012205 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012206 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012207 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080012208 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012209 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012210 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012211 }
12212
12213 private void ensureRunningOnConnectivityServiceThread() {
12214 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
12215 throw new IllegalStateException("Not running on ConnectivityService thread: "
12216 + Thread.currentThread().getName());
12217 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012218 }
12219
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012220 /**
12221 * Update network activity and call BatteryStats to update radio power state if the
12222 * mobile or Wi-Fi activity is changed.
12223 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
12224 * mobile network is active since BatteryStatsService only maintains a single power state
12225 * for the mobile network.
12226 * The Wi-Fi network is also the same.
12227 *
12228 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
12229 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
12230 * transports.
12231 */
12232 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
12233 final boolean isActive, final int uid) {
12234 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
12235 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
12236 + transportType);
12237 return;
12238 }
12239 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
12240 ? mActiveWifiNetworks : mActiveCellularNetworks;
12241
12242 final boolean wasEmpty = activeNetworks.isEmpty();
12243 if (isActive) {
12244 activeNetworks.add(netId);
12245 } else {
12246 activeNetworks.remove(netId);
12247 }
12248
12249 if (wasEmpty != activeNetworks.isEmpty()) {
12250 updateRadioPowerState(isActive, transportType, uid);
12251 }
12252 }
12253
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012254 private void handleDefaultNetworkActivity(final int transportType,
12255 final boolean isActive, final long timestampNs) {
12256 mIsDefaultNetworkActive = isActive;
12257 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
12258 isActive, timestampNs);
12259 if (isActive) {
12260 reportNetworkActive();
12261 }
12262 }
12263
12264 private void handleReportNetworkActivityWithNetIdLabel(
12265 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012266 final int netId = activityParams.label;
12267 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012268 if (idleTimerParams == null) {
12269 // This network activity change is not tracked anymore
12270 // This can happen if netd callback post activity change event message but idle
12271 // timer is removed before processing this message.
12272 return;
12273 }
12274 // TODO: if a network changes transports, storing the transport type in the
12275 // IdleTimerParams is not correct. Consider getting it from the network's
12276 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012277 final int transportType = idleTimerParams.transportType;
12278 maybeUpdateRadioPowerState(netId, transportType,
12279 activityParams.isActive, activityParams.uid);
12280
12281 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
12282 // This activity change is not for the default network.
12283 return;
12284 }
12285
12286 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012287 activityParams.timestampNs);
12288 }
12289
12290 private void handleReportNetworkActivityWithTransportTypeLabel(
12291 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012292 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012293 // This activity change is not for the current default network.
12294 // This can happen if netd callback post activity change event message but
12295 // the default network is lost before processing this message.
12296 return;
12297 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012298 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
12299 activityParams.timestampNs);
12300 }
12301
12302 /**
12303 * Handle network activity change
12304 */
12305 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
12306 ensureRunningOnConnectivityServiceThread();
12307 if (mTrackMultiNetworkActivities) {
12308 handleReportNetworkActivityWithNetIdLabel(activityParams);
12309 } else {
12310 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080012311 }
12312 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012313
lucaslin1193a5d2021-01-21 02:04:15 +080012314 private void reportNetworkActive() {
12315 final int length = mNetworkActivityListeners.beginBroadcast();
12316 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
12317 try {
12318 for (int i = 0; i < length; i++) {
12319 try {
12320 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
12321 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012322 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080012323 }
12324 }
12325 } finally {
12326 mNetworkActivityListeners.finishBroadcast();
12327 }
12328 }
12329
lucaslin1a8b4c62021-01-21 02:02:55 +080012330 // This is deprecated and only to support legacy use cases.
12331 private int transportTypeToLegacyType(int type) {
12332 switch (type) {
12333 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012334 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012335 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012336 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012337 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012338 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012339 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012340 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012341 default:
12342 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12343 }
12344 return ConnectivityManager.TYPE_NONE;
12345 }
12346
12347 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12348 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12349 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12350 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12351 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12352 final long ident = Binder.clearCallingIdentity();
12353 try {
12354 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12355 RECEIVE_DATA_ACTIVITY_CHANGE,
12356 null /* resultReceiver */,
12357 null /* scheduler */,
12358 0 /* initialCode */,
12359 null /* initialData */,
12360 null /* initialExtra */);
12361 } finally {
12362 Binder.restoreCallingIdentity(ident);
12363 }
12364 }
12365
12366 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012367 * Get idle timer label
12368 */
12369 @VisibleForTesting
12370 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12371 final int netId, final int transportType) {
12372 return trackMultiNetworkActivities ? netId : transportType;
12373 }
12374
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012375 private boolean maybeCreateIdleTimer(
12376 String iface, int netId, int timeout, int transportType) {
12377 if (timeout <= 0 || iface == null) return false;
12378 try {
12379 final String label = Integer.toString(getIdleTimerLabel(
12380 mTrackMultiNetworkActivities, netId, transportType));
12381 mNetd.idletimerAddInterface(iface, timeout, label);
12382 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12383 return true;
12384 } catch (Exception e) {
12385 loge("Exception in createIdleTimer", e);
12386 return false;
12387 }
12388 }
12389
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012390 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012391 * Setup data activity tracking for the given network.
12392 *
12393 * Every {@code setupDataActivityTracking} should be paired with a
12394 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012395 *
12396 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012397 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012398 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012399 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012400 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012401 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012402
12403 final int timeout;
12404 final int type;
12405
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012406 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12407 // Do not track VPN network.
12408 return false;
12409 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012410 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12411 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012412 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012413 10);
12414 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12415 } else if (networkAgent.networkCapabilities.hasTransport(
12416 NetworkCapabilities.TRANSPORT_WIFI)) {
12417 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012418 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012419 15);
12420 type = NetworkCapabilities.TRANSPORT_WIFI;
12421 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012422 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012423 }
12424
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012425 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12426 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12427 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12428 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12429 // state only about a network that has an idletimer.
12430 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012431 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012432 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012433 }
12434
12435 /**
12436 * Remove data activity tracking when network disconnects.
12437 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012438 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12439 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012440 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012441 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012442 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12443
lucaslinb961efc2021-01-21 02:03:17 +080012444 if (iface == null) return;
12445
12446 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012447 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12448 // Do not track VPN network.
12449 return;
12450 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012451 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12452 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12453 type = NetworkCapabilities.TRANSPORT_WIFI;
12454 } else {
12455 return; // do not track any other networks
12456 }
12457
12458 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012459 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012460 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012461 if (params == null) {
12462 // IdleTimer is not added if the configured timeout is 0 or negative value
12463 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012464 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012465 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012466 final String label = Integer.toString(getIdleTimerLabel(
12467 mTrackMultiNetworkActivities, netId, params.transportType));
12468 // The call fails silently if no idle timer setup for this interface
12469 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012470 } catch (Exception e) {
12471 // You shall not crash!
12472 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012473 }
12474 }
12475
Motomu Utsumi6225d572023-05-29 15:08:57 +090012476 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12477 boolean hasIdleTimer) {
12478 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012479 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012480 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012481 // If only the default network is tracked, callbacks are called only when the
12482 // network has the idle timer.
12483 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012484 reportNetworkActive();
12485 }
12486 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012487 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012488 // If there is no default network, default network is considered active to keep the
12489 // existing behavior.
12490 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012491 }
12492 }
12493
lucaslin1a8b4c62021-01-21 02:02:55 +080012494 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012495 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012496 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012497 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012498 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012499 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012500 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12501 // first connected and remove when the network is disconnected.
12502 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12503 // becomes the default network and remove when the network becomes no longer the default
12504 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012505 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012506 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012507 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012508 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012509 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012510 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012511 removeDataActivityTracking(oldNetwork);
12512 }
12513 }
lucaslinb961efc2021-01-21 02:03:17 +080012514
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012515 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012516 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12517 switch (transportType) {
12518 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012519 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012520 break;
12521 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012522 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012523 break;
12524 default:
12525 logw("Untracked transport type:" + transportType);
12526 }
12527 }
lucaslin1193a5d2021-01-21 02:04:15 +080012528
12529 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012530 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012531 }
12532
12533 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12534 mNetworkActivityListeners.register(l);
12535 }
12536
12537 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12538 mNetworkActivityListeners.unregister(l);
12539 }
lucaslin012f7a12021-01-21 02:04:35 +080012540
12541 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012542 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012543 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012544 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012545 pw.println("Idle timers:");
12546 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012547 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12548 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12549 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012550 pw.print(" timeout="); pw.print(params.timeout);
12551 pw.print(" type="); pw.println(params.transportType);
12552 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012553 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12554 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012555 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012556 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12557 // be accessed from handler thread, except dump(). As dump() is never called in
12558 // normal usage, it would be needlessly expensive to lock the collection only for
12559 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012560 // So catching the exception and logging.
12561 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012562 }
12563 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012564 }
James Mattis47db0582021-01-01 14:13:35 -080012565
Daniel Brightf9e945b2020-06-15 16:10:01 -070012566 /**
12567 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12568 *
12569 * @param socketInfo the socket information
12570 * @param callback the callback to register
12571 */
12572 @Override
12573 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12574 @NonNull final IQosCallback callback) {
12575 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12576 if (nai == null || nai.networkCapabilities == null) {
12577 try {
12578 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12579 } catch (final RemoteException ex) {
12580 loge("registerQosCallbackInternal: RemoteException", ex);
12581 }
12582 return;
12583 }
12584 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12585 }
12586
12587 /**
12588 * Register a {@link IQosCallback} with base {@link QosFilter}.
12589 *
12590 * @param filter the filter to register
12591 * @param callback the callback to register
12592 * @param nai the agent information related to the filter's network
12593 */
12594 @VisibleForTesting
12595 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12596 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012597 Objects.requireNonNull(filter, "filter must be non-null");
12598 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012599
12600 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012601 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12602 // on this network is unregistered when the app loses permission or b) no QoS
12603 // callbacks are sent for restricted networks unless the app currently has permission
12604 // to access restricted networks.
12605 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012606 }
12607 mQosCallbackTracker.registerCallback(callback, filter, nai);
12608 }
12609
12610 /**
12611 * Unregisters the given callback.
12612 *
12613 * @param callback the callback to unregister
12614 */
12615 @Override
12616 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012617 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012618 mQosCallbackTracker.unregisterCallback(callback);
12619 }
James Mattis47db0582021-01-01 14:13:35 -080012620
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012621 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12622 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12623 // Enterprise device can be fully managed like device owner and such use case
12624 // also should be supported. Calling app check for work profile and fully managed device
12625 // is already done in DevicePolicyManager.
12626 // This check is an extra caution to be sure device is fully managed or not.
12627 final UserManager um = mContext.getSystemService(UserManager.class);
12628 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12629 if (um.isManagedProfile(profile.getIdentifier())) {
12630 return true;
12631 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012632 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012633 return false;
12634 }
12635
James Mattis45d81842021-01-10 14:24:24 -080012636 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012637 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012638 *
12639 * See the documentation for the individual preferences for a description of the supported
12640 * behaviors.
12641 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012642 * @param profile If the device owner is set, any profile is allowed.
12643 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012644 * @param preferences the list of profile network preferences for the
12645 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012646 * @param listener an optional listener to listen for completion of the operation.
12647 */
12648 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012649 public void setProfileNetworkPreferences(
12650 @NonNull final UserHandle profile,
12651 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012652 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012653 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012654 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012655
12656 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012657 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12658 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12659 .build();
12660 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012661 }
12662
paulhu3ffffe72021-09-16 10:15:22 +080012663 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012664 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012665 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012666 }
12667 if (profile.getIdentifier() < 0) {
12668 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12669 + "UserHandle.CURRENT not supported)");
12670 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012671 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12672 throw new IllegalArgumentException("Profile must be a managed profile "
12673 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012674 }
paulhuaa0743d2021-05-26 21:56:03 +080012675
Chalard Jean0606fc82022-12-14 20:34:43 +090012676 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012677 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012678 for (final ProfileNetworkPreference preference : preferences) {
12679 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012680 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012681 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012682 switch (preference.getPreference()) {
12683 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12684 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012685 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012686 if (preference.getPreferenceEnterpriseId() != 0) {
12687 throw new IllegalArgumentException(
12688 "Invalid enterprise identifier in setProfileNetworkPreferences");
12689 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012690 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012691 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12692 blockingNonEnterprise = true;
12693 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012694 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12695 allowFallback = false;
12696 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012697 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012698 // This code is needed even though there is a check later on,
12699 // because isRangeAlreadyInPreferenceList assumes that every preference
12700 // has a UID list.
12701 if (hasDefaultPreference) {
12702 throw new IllegalArgumentException(
12703 "Default profile preference should not be set along with other "
12704 + "preference");
12705 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012706 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12707 throw new IllegalArgumentException(
12708 "Invalid enterprise identifier in setProfileNetworkPreferences");
12709 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012710 final Set<UidRange> uidRangeSet =
12711 getUidListToBeAppliedForNetworkPreference(profile, preference);
12712 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12713 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12714 } else {
12715 throw new IllegalArgumentException(
12716 "Overlapping uid range in setProfileNetworkPreferences");
12717 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012718 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012719 nc.addEnterpriseId(
12720 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012721 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12722 break;
12723 default:
12724 throw new IllegalArgumentException(
12725 "Invalid preference in setProfileNetworkPreferences");
12726 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012727 preferenceList.add(new ProfileNetworkPreferenceInfo(
12728 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012729 if (hasDefaultPreference && preferenceList.size() > 1) {
12730 throw new IllegalArgumentException(
12731 "Default profile preference should not be set along with other preference");
12732 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012733 }
12734 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012735 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012736 }
12737
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012738 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12739 @NonNull final UserHandle profile,
12740 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12741 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012742 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12743 profileNetworkPreference.getIncludedUids());
12744
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012745 if (uidRangeSet.size() > 0) {
12746 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12747 throw new IllegalArgumentException(
12748 "Allow uid range is outside the uid range of profile.");
12749 }
12750 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012751 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012752 profileNetworkPreference.getExcludedUids());
12753 if (disallowUidRangeSet.size() > 0) {
12754 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12755 throw new IllegalArgumentException(
12756 "disallow uid range is outside the uid range of profile.");
12757 }
12758 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12759 disallowUidRangeSet);
12760 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012761 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012762 uidRangeSet.add(profileUids);
12763 }
12764 }
12765 return uidRangeSet;
12766 }
12767
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012768 private boolean isEnterpriseIdentifierValid(
12769 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012770 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012771 return true;
12772 }
12773 return false;
12774 }
12775
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012776 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012777 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012778 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012779 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012780 // The NRI for a user should contain the request for capabilities.
12781 // If fallback to default network is needed then NRI should include
12782 // the request for the default network. Create an image of it to
12783 // have the correct UIDs in it (also a request can only be part of one NRI, because
12784 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012785 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12786 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012787 if (pref.allowFallback) {
12788 nrs.add(createDefaultInternetRequestForTransport(
12789 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12790 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012791 if (VDBG) {
12792 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12793 pref.capabilities.getUids()));
12794 }
12795
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012796 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012797 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012798 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012799 result.add(nri);
12800 }
12801 return result;
12802 }
12803
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012804 /**
12805 * Compare if the given UID range sets have the same UIDs.
12806 *
12807 */
12808 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012809 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012810 @NonNull Set<UidRange> uidRangeSet) {
12811 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12812 return false;
12813 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012814 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012815 if (UidRangeUtils.doesRangeSetOverlap(
12816 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12817 return true;
12818 }
12819 }
12820 return false;
12821 }
12822
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012823 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012824 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012825 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012826 /*
12827 * handleSetProfileNetworkPreference is always called for single user.
12828 * preferenceList only contains preferences for different uids within the same user
12829 * (enforced by getUidListToBeAppliedForNetworkPreference).
12830 * Clear all the existing preferences for the user before applying new preferences.
12831 *
12832 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012833 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12834 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012835 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12836 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012837
paulhu74128522021-09-28 02:29:03 +000012838 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12839 addPerAppDefaultNetworkRequests(
12840 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012841 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012842
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012843 // Finally, rematch.
12844 rematchAllNetworksAndRequests();
12845
12846 if (null != listener) {
12847 try {
12848 listener.onComplete();
12849 } catch (RemoteException e) {
12850 loge("Listener for setProfileNetworkPreference has died");
12851 }
12852 }
12853 }
12854
paulhu51f77dc2021-06-07 02:34:20 +000012855 @VisibleForTesting
12856 @NonNull
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012857 ArraySet<NetworkRequestInfo> createNrisForPreferenceOrder(@NonNull final Set<Integer> uids,
12858 @NonNull final List<NetworkRequest> requests,
12859 final int preferenceOrder) {
paulhu51f77dc2021-06-07 02:34:20 +000012860 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12861 if (uids.size() == 0) {
12862 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12863 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
paulhu51f77dc2021-06-07 02:34:20 +000012864 return nris;
12865 }
12866
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012867 final Set<UidRange> ranges = new ArraySet<>();
12868 for (final int uid : uids) {
12869 ranges.add(new UidRange(uid, uid));
12870 }
12871 setNetworkRequestUids(requests, ranges);
12872 nris.add(new NetworkRequestInfo(Process.myUid(), requests, preferenceOrder));
12873 return nris;
12874 }
12875
12876 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12877 @NonNull final Set<Integer> uids) {
paulhu51f77dc2021-06-07 02:34:20 +000012878 final List<NetworkRequest> requests = new ArrayList<>();
12879 // The NRI should be comprised of two layers:
12880 // - The request for the mobile network preferred.
12881 // - The request for the default network, for fallback.
12882 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012883 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012884 requests.add(createDefaultInternetRequestForTransport(
12885 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012886 return createNrisForPreferenceOrder(uids, requests, PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED
12887 );
12888 }
12889
12890 ArraySet<NetworkRequestInfo> createMultiLayerNrisFromSatelliteNetworkFallbackUids(
12891 @NonNull final Set<Integer> uids) {
12892 final List<NetworkRequest> requests = new ArrayList<>();
12893
12894 // request: track default(unrestricted internet network)
12895 requests.add(createDefaultInternetRequestForTransport(
12896 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12897
12898 // request: restricted Satellite internet
12899 final NetworkCapabilities cap = new NetworkCapabilities.Builder()
12900 .addCapability(NET_CAPABILITY_INTERNET)
12901 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
12902 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED)
12903 .addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE)
12904 .build();
12905 requests.add(createNetworkRequest(NetworkRequest.Type.REQUEST, cap));
12906
12907 return createNrisForPreferenceOrder(uids, requests, PREFERENCE_ORDER_SATELLITE_FALLBACK);
paulhu51f77dc2021-06-07 02:34:20 +000012908 }
12909
12910 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012911 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012912 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12913 addPerAppDefaultNetworkRequests(
12914 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012915 // Finally, rematch.
12916 rematchAllNetworksAndRequests();
12917 }
12918
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012919 private void handleSetSatelliteNetworkPreference(
12920 @NonNull final Set<Integer> satelliteNetworkPreferredUids) {
12921 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_SATELLITE_FALLBACK);
12922 addPerAppDefaultNetworkRequests(
12923 createMultiLayerNrisFromSatelliteNetworkFallbackUids(satelliteNetworkPreferredUids)
12924 );
12925 // Finally, rematch.
12926 rematchAllNetworksAndRequests();
12927 }
12928
Patrick Rohr2857ac42022-01-21 14:58:16 +010012929 private void handleIngressRateLimitChanged() {
12930 final long oldIngressRateLimit = mIngressRateLimit;
12931 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12932 mContext);
12933 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12934 if (canNetworkBeRateLimited(networkAgent)) {
12935 // If rate limit has previously been enabled, remove the old limit first.
12936 if (oldIngressRateLimit >= 0) {
12937 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12938 }
12939 if (mIngressRateLimit >= 0) {
12940 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12941 mIngressRateLimit);
12942 }
12943 }
12944 }
12945 }
12946
12947 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012948 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012949 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012950
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012951 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12952 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12953 // internet connectivity can be rate limited.
12954 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12955 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012956 return false;
12957 }
12958
12959 final String iface = networkAgent.linkProperties.getInterfaceName();
12960 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012961 // This may happen in tests, but if there is no interface then there is nothing that
12962 // can be rate limited.
12963 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012964 return false;
12965 }
12966 return true;
12967 }
12968
James Mattis45d81842021-01-10 14:24:24 -080012969 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012970 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12971 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012972 }
12973
12974 /**
12975 * Used by automotive devices to set the network preferences used to direct traffic at an
12976 * application level as per the given OemNetworkPreferences. An example use-case would be an
12977 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12978 * vehicle via a particular network.
12979 *
12980 * Calling this will overwrite the existing preference.
12981 *
James Mattisda32cfe2021-01-26 16:23:52 -080012982 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012983 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012984 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012985 */
James Mattis47db0582021-01-01 14:13:35 -080012986 @Override
James Mattis45d81842021-01-10 14:24:24 -080012987 public void setOemNetworkPreference(
12988 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012989 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012990
James Mattisfa270db2021-05-31 17:11:10 -070012991 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12992 // Only bypass the permission/device checks if this is a valid test request.
12993 if (isValidTestOemNetworkPreference(preference)) {
12994 enforceManageTestNetworksPermission();
12995 } else {
12996 enforceAutomotiveDevice();
12997 enforceOemNetworkPreferencesPermission();
12998 validateOemNetworkPreferences(preference);
12999 }
James Mattis45d81842021-01-10 14:24:24 -080013000
James Mattis45d81842021-01-10 14:24:24 -080013001 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
13002 new Pair<>(preference, listener)));
13003 }
13004
James Mattisfa270db2021-05-31 17:11:10 -070013005 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000013006 * Sets the specified UIDs to get/receive the VPN as the only default network.
13007 *
13008 * Calling this will overwrite the existing network preference for this session, and the
13009 * specified UIDs won't get any default network when no VPN is connected.
13010 *
13011 * @param session The VPN session which manages the passed UIDs.
13012 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
13013 * setting for this session if the array is empty. Null is not allowed, the
13014 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
13015 * @hide
13016 */
13017 @Override
13018 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
13019 Objects.requireNonNull(ranges);
13020 enforceNetworkStackOrSettingsPermission();
13021 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
13022 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
13023 throw new IllegalArgumentException(
13024 "setVpnNetworkPreference: Passed UID ranges overlap");
13025 }
13026
13027 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
13028 new VpnNetworkPreferenceInfo(session,
13029 new ArraySet<UidRange>(Arrays.asList(ranges)))));
13030 }
13031
13032 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
13033 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
13034
13035 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
13036 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
13037
13038 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
13039 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
13040 // Finally, rematch.
13041 rematchAllNetworksAndRequests();
13042 }
13043
13044 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
13045 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
13046 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
13047 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
13048 final List<NetworkRequest> requests = new ArrayList<>();
13049 // Request VPN only, so other networks won't be the fallback options when VPN is not
13050 // connected temporarily.
13051 requests.add(createVpnRequest());
13052 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
13053 setNetworkRequestUids(requests, uidRanges);
13054 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
13055 }
13056 return nris;
13057 }
13058
13059 /**
James Mattisfa270db2021-05-31 17:11:10 -070013060 * Check the validity of an OEM network preference to be used for testing purposes.
13061 * @param preference the preference to validate
13062 * @return true if this is a valid OEM network preference test request.
13063 */
13064 private boolean isValidTestOemNetworkPreference(
13065 @NonNull final OemNetworkPreferences preference) {
13066 // Allow for clearing of an existing OemNetworkPreference used for testing.
13067 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
13068 // changes after this check is complete. This is an unlikely scenario as calling of this API
13069 // is controlled by the OEM therefore the added complexity is not worth adding given those
13070 // circumstances. That said, it is an edge case to be aware of hence this comment.
13071 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
13072 && isTestOemNetworkPreference(mOemNetworkPreferences);
13073 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
13074 }
13075
13076 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
13077 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
13078 return prefMap.size() == 1
13079 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
13080 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
13081 }
13082
James Mattis45d81842021-01-10 14:24:24 -080013083 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
13084 for (@OemNetworkPreferences.OemNetworkPreference final int pref
13085 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070013086 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
13087 throw new IllegalArgumentException(
13088 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
13089 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080013090 }
13091 }
13092 }
13093
13094 private void handleSetOemNetworkPreference(
13095 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090013096 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080013097 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
13098 if (DBG) {
13099 log("set OEM network preferences :" + preference.toString());
13100 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090013101
James Mattiscb1e0362021-04-06 17:07:42 -070013102 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000013103 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
13104 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
13105 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080013106 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080013107
13108 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090013109 try {
13110 listener.onComplete();
13111 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080013112 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090013113 }
James Mattis45d81842021-01-10 14:24:24 -080013114 }
13115 }
13116
paulhu74128522021-09-28 02:29:03 +000013117 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080013118 // Skip the requests which are set by other network preference. Because the uid range rules
13119 // should stay in netd.
13120 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080013121 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080013122 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080013123 }
13124
James Mattis3ce3d3c2021-02-09 18:18:28 -080013125 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
13126 ensureRunningOnConnectivityServiceThread();
13127 mDefaultNetworkRequests.addAll(nris);
13128 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
13129 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080013130 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000013131 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
13132 nrisToRegister.addAll(
13133 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
13134 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013135 }
13136
13137 /**
13138 * All current requests that are tracking the default network need to be assessed as to whether
13139 * or not the current set of per-application default requests will be changing their default
13140 * network. If so, those requests will need to be updated so that they will send callbacks for
13141 * default network changes at the appropriate time. Additionally, those requests tracking the
13142 * default that were previously updated by this flow will need to be reassessed.
13143 * @return the nris which will need to be updated.
13144 */
13145 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
13146 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
13147 // Get the distinct nris to check since for multilayer requests, it is possible to have the
13148 // same nri in the map's values for each of its NetworkRequest objects.
13149 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080013150 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013151 // Include this nri if it is currently being tracked.
13152 if (isPerAppTrackedNri(nri)) {
13153 defaultCallbackRequests.add(nri);
13154 continue;
13155 }
13156 // We only track callbacks for requests tracking the default.
13157 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
13158 continue;
13159 }
13160 // Include this nri if it will be tracked by the new per-app default requests.
13161 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013162 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080013163 if (isNriGoingToBeTracked) {
13164 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080013165 }
13166 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080013167 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080013168 }
13169
James Mattis3ce3d3c2021-02-09 18:18:28 -080013170 /**
13171 * Create nris for those network requests that are currently tracking the default network that
13172 * are being controlled by a per-application default.
13173 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
13174 * foundation when creating the nri. Important items include the calling uid's original
13175 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
13176 * requests are assumed to have already been validated as needing to be updated.
13177 * @return the Set of nris to use when registering network requests.
13178 */
13179 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
13180 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
13181 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
13182 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
13183 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013184 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013185
Chalard Jean9473c982021-07-29 20:03:04 +090013186 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080013187 if (trackingNri == mDefaultRequest) {
13188 callbackRequestsToRegister.add(new NetworkRequestInfo(
13189 callbackRequest,
13190 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
13191 continue;
13192 }
13193
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013194 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013195 callbackRequestsToRegister.add(new NetworkRequestInfo(
13196 callbackRequest,
13197 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013198 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090013199 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080013200 }
13201 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080013202 }
13203
Chalard Jean17215832021-03-01 14:06:28 +090013204 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
13205 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090013206 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000013207 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090013208 }
13209 }
13210
James Mattis45d81842021-01-10 14:24:24 -080013211 /**
13212 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
13213 */
13214 @VisibleForTesting
13215 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013216 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080013217 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013218 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080013219 final SparseArray<Set<Integer>> uids =
13220 createUidsFromOemNetworkPreferences(preference);
13221 for (int i = 0; i < uids.size(); i++) {
13222 final int key = uids.keyAt(i);
13223 final Set<Integer> value = uids.valueAt(i);
13224 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
13225 // No need to add an nri without any requests.
13226 if (0 == nri.mRequests.size()) {
13227 continue;
13228 }
13229 nris.add(nri);
13230 }
13231
13232 return nris;
13233 }
13234
13235 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
13236 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070013237 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080013238 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080013239 final List<UserHandle> users =
13240 mContext.getSystemService(UserManager.class).getUserHandles(true);
13241 if (null == users || users.size() == 0) {
13242 if (VDBG || DDBG) {
13243 log("No users currently available for setting the OEM network preference.");
13244 }
James Mattisb6b6a432021-06-01 22:30:36 -070013245 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080013246 }
James Mattis45d81842021-01-10 14:24:24 -080013247 for (final Map.Entry<String, Integer> entry :
13248 preference.getNetworkPreferences().entrySet()) {
13249 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070013250 // Add the rules for all users as this policy is device wide.
13251 for (final UserHandle user : users) {
13252 try {
13253 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
13254 if (!prefToUids.contains(pref)) {
13255 prefToUids.put(pref, new ArraySet<>());
13256 }
13257 prefToUids.get(pref).add(uid);
13258 } catch (PackageManager.NameNotFoundException e) {
13259 // Although this may seem like an error scenario, it is ok that uninstalled
13260 // packages are sent on a network preference as the system will watch for
13261 // package installations associated with this network preference and update
13262 // accordingly. This is done to minimize race conditions on app install.
13263 continue;
James Mattis45d81842021-01-10 14:24:24 -080013264 }
James Mattis45d81842021-01-10 14:24:24 -080013265 }
13266 }
James Mattisb6b6a432021-06-01 22:30:36 -070013267 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080013268 }
13269
13270 private NetworkRequestInfo createNriFromOemNetworkPreferences(
13271 @OemNetworkPreferences.OemNetworkPreference final int preference,
13272 @NonNull final Set<Integer> uids) {
13273 final List<NetworkRequest> requests = new ArrayList<>();
13274 // Requests will ultimately be evaluated by order of insertion therefore it matters.
13275 switch (preference) {
13276 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
13277 requests.add(createUnmeteredNetworkRequest());
13278 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070013279 requests.add(createDefaultInternetRequestForTransport(
13280 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080013281 break;
13282 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
13283 requests.add(createUnmeteredNetworkRequest());
13284 requests.add(createOemPaidNetworkRequest());
13285 break;
13286 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
13287 requests.add(createOemPaidNetworkRequest());
13288 break;
13289 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
13290 requests.add(createOemPrivateNetworkRequest());
13291 break;
James Mattisfa270db2021-05-31 17:11:10 -070013292 case OEM_NETWORK_PREFERENCE_TEST:
13293 requests.add(createUnmeteredNetworkRequest());
13294 requests.add(createTestNetworkRequest());
13295 requests.add(createDefaultRequest());
13296 break;
13297 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
13298 requests.add(createTestNetworkRequest());
13299 break;
James Mattis45d81842021-01-10 14:24:24 -080013300 default:
13301 // This should never happen.
13302 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
13303 + " called with invalid preference of " + preference);
13304 }
13305
James Mattisfa270db2021-05-31 17:11:10 -070013306 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090013307 for (final int uid : uids) {
13308 ranges.add(new UidRange(uid, uid));
13309 }
13310 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080013311 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080013312 }
13313
13314 private NetworkRequest createUnmeteredNetworkRequest() {
13315 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13316 .addCapability(NET_CAPABILITY_NOT_METERED)
13317 .addCapability(NET_CAPABILITY_VALIDATED);
13318 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
13319 }
13320
13321 private NetworkRequest createOemPaidNetworkRequest() {
13322 // NET_CAPABILITY_OEM_PAID is a restricted capability.
13323 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13324 .addCapability(NET_CAPABILITY_OEM_PAID)
13325 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13326 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13327 }
13328
13329 private NetworkRequest createOemPrivateNetworkRequest() {
13330 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
13331 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13332 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
13333 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13334 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13335 }
13336
13337 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070013338 final NetworkCapabilities netcap = new NetworkCapabilities();
13339 netcap.addCapability(NET_CAPABILITY_INTERNET);
13340 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
13341 return netcap;
13342 }
13343
13344 private NetworkRequest createTestNetworkRequest() {
13345 final NetworkCapabilities netcap = new NetworkCapabilities();
13346 netcap.clearAll();
13347 netcap.addTransportType(TRANSPORT_TEST);
13348 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080013349 }
James Mattis47db0582021-01-01 14:13:35 -080013350 }
markchien738ad912021-12-09 18:15:45 +080013351
Junyu Lai38c75032023-12-04 07:52:19 +000013352 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080013353 @Override
Junyu Laidf210362023-10-24 02:47:50 +000013354 public void setDataSaverEnabled(final boolean enable) {
13355 enforceNetworkStackOrSettingsPermission();
13356 try {
13357 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
13358 if (!ret) {
13359 throw new IllegalStateException("Error when changing iptables: " + enable);
13360 }
13361 } catch (RemoteException e) {
13362 // Lack of permission or binder errors.
13363 throw new IllegalStateException(e);
13364 }
Ken Chen24330172023-10-20 13:02:14 +080013365
13366 try {
13367 mBpfNetMaps.setDataSaverEnabled(enable);
13368 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13369 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13370 }
Junyu Laidf210362023-10-24 02:47:50 +000013371 }
13372
13373 @Override
markchien738ad912021-12-09 18:15:45 +080013374 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13375 enforceNetworkStackOrSettingsPermission();
13376
13377 try {
13378 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013379 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013380 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013381 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013382 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013383 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013384 throw new IllegalStateException(e);
13385 }
13386 }
13387
13388 @Override
13389 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13390 enforceNetworkStackOrSettingsPermission();
13391
13392 try {
13393 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013394 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013395 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013396 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013397 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013398 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013399 throw new IllegalStateException(e);
13400 }
13401 }
markchiene1561fa2021-12-09 22:00:56 +080013402
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013403 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13404 throws PackageManager.NameNotFoundException {
13405 final PackageManager pm = mContext.getPackageManager();
13406 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13407 if (appId < Process.FIRST_APPLICATION_UID) {
13408 throw new RuntimeException("Can't set package firewall rule for system app "
13409 + packageName + " with appId " + appId);
13410 }
13411 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13412 final int uid = uh.getUid(appId);
13413 setUidFirewallRule(chain, uid, rule);
13414 }
13415 return appId;
13416 }
13417
markchiene1561fa2021-12-09 22:00:56 +080013418 @Override
markchien3c04e662022-03-22 16:29:56 +080013419 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013420 enforceNetworkStackOrSettingsPermission();
13421
markchien3c04e662022-03-22 16:29:56 +080013422 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13423 int firewallRule = getFirewallRuleType(chain, rule);
13424
13425 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13426 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13427 }
13428
markchiene1561fa2021-12-09 22:00:56 +080013429 try {
markchien3c04e662022-03-22 16:29:56 +080013430 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013431 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013432 throw new IllegalStateException(e);
13433 }
13434 }
markchien98a6f952022-01-13 23:43:53 +080013435
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013436 private int getPackageFirewallRule(final int chain, final String packageName)
13437 throws PackageManager.NameNotFoundException {
13438 final PackageManager pm = mContext.getPackageManager();
13439 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13440 return getUidFirewallRule(chain, appId);
13441 }
13442
Motomu Utsumi900b8062023-01-19 16:16:49 +090013443 @Override
13444 public int getUidFirewallRule(final int chain, final int uid) {
13445 enforceNetworkStackOrSettingsPermission();
13446 return mBpfNetMaps.getUidRule(chain, uid);
13447 }
13448
markchien3c04e662022-03-22 16:29:56 +080013449 private int getFirewallRuleType(int chain, int rule) {
13450 final int defaultRule;
13451 switch (chain) {
13452 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013453 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13454 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013455 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013456 defaultRule = FIREWALL_RULE_ALLOW;
13457 break;
13458 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13459 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13460 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13461 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013462 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013463 defaultRule = FIREWALL_RULE_DENY;
13464 break;
13465 default:
13466 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13467 }
13468 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13469
13470 return rule;
13471 }
13472
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013473 private void closeSocketsForFirewallChainLocked(final int chain)
13474 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013475 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013476 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13477 // So, close all non-system socket owned by uids that are not explicitly allowed
13478 Set<Range<Integer>> ranges = new ArraySet<>();
13479 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13480 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13481 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13482 } else {
13483 // Denylist means the firewall allows all by default, uids must be explicitly denied
13484 // So, close socket owned by uids that are explicitly denied
13485 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13486 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13487 }
13488 }
13489
markchien98a6f952022-01-13 23:43:53 +080013490 @Override
13491 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13492 enforceNetworkStackOrSettingsPermission();
13493
13494 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013495 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013496 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013497 throw new IllegalStateException(e);
13498 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013499
Chalard Jeandf29a852023-05-29 17:02:43 +090013500 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013501 try {
13502 closeSocketsForFirewallChainLocked(chain);
13503 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13504 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13505 }
13506 }
markchien98a6f952022-01-13 23:43:53 +080013507 }
13508
markchien00a0bed2022-01-13 23:46:13 +080013509 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013510 public boolean getFirewallChainEnabled(final int chain) {
13511 enforceNetworkStackOrSettingsPermission();
13512
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013513 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013514 }
13515
13516 @Override
markchien00a0bed2022-01-13 23:46:13 +080013517 public void replaceFirewallChain(final int chain, final int[] uids) {
13518 enforceNetworkStackOrSettingsPermission();
13519
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013520 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013521 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013522
13523 @Override
13524 public IBinder getCompanionDeviceManagerProxyService() {
13525 enforceNetworkStackPermission(mContext);
13526 return mCdmps;
13527 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013528
13529 @Override
13530 public IBinder getRoutingCoordinatorService() {
13531 enforceNetworkStackPermission(mContext);
13532 return mRoutingCoordinatorService;
13533 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013534}