blob: 1c924889e0fcb0e8724177306a7ebd28aaee11d1 [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;
markchien3c04e662022-03-22 16:29:56 +080041import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
42import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
43import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090044import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090045import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090046import static android.net.ConnectivityManager.TYPE_MOBILE;
47import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
48import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
49import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
50import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
51import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
52import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
53import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
54import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
55import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070056import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090057import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070058import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090059import static android.net.ConnectivityManager.TYPE_WIFI;
60import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070061import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070062import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080063import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080064import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080065import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070066import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080067import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Yang Sunca537d52024-01-19 12:53:50 +080068import static android.net.MulticastRoutingConfig.FORWARD_NONE;
Paul Jensen53f08952015-06-16 14:27:36 -040069import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090070import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090071import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Chalard Jeane0aaca52023-10-17 13:23:07 +090073import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090075import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
76import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060077import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080079import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090080import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080081import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
82import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080083import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Chalard Jeanf95e2de2023-08-22 19:07:47 +090084import static android.net.NetworkCapabilities.NET_CAPABILITY_TEMPORARILY_NOT_METERED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090085import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080086import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
87import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080088import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
89import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
90import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090091import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090092import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060093import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070094import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080095import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090096import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070097import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
98import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070099import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +0800100import static android.os.Process.VPN_UID;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100101import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700102import static android.system.OsConstants.IPPROTO_TCP;
103import static android.system.OsConstants.IPPROTO_UDP;
Chalard Jeaneb663892023-10-07 15:17:07 +0900104
Junyu Lai155760b2023-10-05 14:51:00 +0800105import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET4_BIND;
106import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET6_BIND;
107import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_EGRESS;
108import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_INGRESS;
109import static com.android.net.module.util.BpfUtils.BPF_CGROUP_INET_SOCK_CREATE;
Xiao Ma60142372022-07-16 17:30:20 +0900110import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
paulhu3ffffe72021-09-16 10:15:22 +0800111import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
112import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
113import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Junyu Lai71b51532024-02-01 10:39:01 +0800114import static com.android.net.module.util.PermissionUtils.hasAnyPermissionOf;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900115import static com.android.server.ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE;
Ying Xu7cabd322024-01-15 18:40:15 -0800116import static com.android.server.connectivity.CarrierPrivilegeAuthenticator.CarrierPrivilegesLostListener;
117import static com.android.server.connectivity.ConnectivityFlags.REQUEST_RESTRICTED_WIFI;
Chalard Jeaneb663892023-10-07 15:17:07 +0900118
Chalard Jean5b639762020-03-09 21:25:37 +0900119import android.Manifest;
Junyu Lai71b51532024-02-01 10:39:01 +0800120import android.annotation.CheckResult;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000121import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800122import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600123import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800124import android.annotation.TargetApi;
Mark Fasheh7c999d82023-05-04 20:23:11 +0000125import android.app.ActivityManager;
126import android.app.ActivityManager.UidFrozenStateChangedCallback;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800127import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800128import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700129import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700130import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900131import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800132import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700133import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800134import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800135import android.content.ContentResolver;
136import android.content.Context;
137import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700138import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800139import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900140import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700141import android.database.ContentObserver;
Junyu Laie0031522023-08-29 18:32:57 +0800142import android.net.BpfNetMapsUtils;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900143import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900144import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700145import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800146import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800147import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800148import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900149import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800150import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900151import android.net.ConnectivityManager.RestrictBackgroundStatus;
paulhu90a7a512021-03-17 17:19:09 +0800152import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900153import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800154import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700155import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900156import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800157import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800158import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800159import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800160import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800161import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900162import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900163import android.net.INetworkMonitor;
164import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900165import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900166import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700167import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800168import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900169import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900170import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900171import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800172import android.net.LinkProperties;
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +0900173import android.net.LocalNetworkConfig;
Chalard Jean22350c92023-10-07 19:21:45 +0900174import android.net.LocalNetworkInfo;
Charles He9369e612017-05-15 17:07:18 +0100175import android.net.MatchAllNetworkSpecifier;
Yang Sun29037f62023-12-04 10:31:58 +0800176import android.net.MulticastRoutingConfig;
Ken Chen6df7a902021-04-09 15:08:42 +0800177import android.net.NativeNetworkConfig;
178import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800179import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700180import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700181import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900182import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700183import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800184import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700185import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900186import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900187import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000188import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900189import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700190import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900191import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700192import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900193import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700194import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800195import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900196import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700197import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000198import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800199import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900200import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800201import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400202import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700203import android.net.QosCallbackException;
204import android.net.QosFilter;
205import android.net.QosSocketFilter;
206import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700207import android.net.RouteInfo;
junyulai011b1f12019-01-03 18:50:15 +0800208import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800209import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900210import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400211import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800212import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800213import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400214import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800215import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900216import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900217import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900218import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900219import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800220import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900221import android.net.networkstack.ModuleNetworkStackClient;
222import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900223import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800224import android.net.resolv.aidl.DnsHealthEventParcel;
225import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
226import android.net.resolv.aidl.Nat64PrefixEventParcel;
227import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900228import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900229import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800230import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800231import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800232import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700233import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000234import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800235import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700236import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700237import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800238import android.os.Looper;
239import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700240import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700241import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900242import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800243import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700244import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700245import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800246import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700247import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900248import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900249import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700250import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700251import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400252import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800253import android.provider.Settings;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900254import android.stats.connectivity.MeteredState;
255import android.stats.connectivity.RequestType;
256import android.stats.connectivity.ValidatedState;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900257import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700258import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700259import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700260import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800261import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900262import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000263import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600264import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900265import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900266import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700267import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700268import android.util.SparseIntArray;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900269import android.util.StatsEvent;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800270
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800271import androidx.annotation.RequiresApi;
272
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900273import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400274import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400275import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700276import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900277import com.android.internal.util.MessageUtils;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900278import com.android.metrics.ConnectionDurationForTransports;
279import com.android.metrics.ConnectionDurationPerTransports;
280import com.android.metrics.ConnectivitySampleMetricsHelper;
281import com.android.metrics.ConnectivityStateSample;
282import com.android.metrics.NetworkCountForTransports;
283import com.android.metrics.NetworkCountPerTransports;
284import com.android.metrics.NetworkDescription;
285import com.android.metrics.NetworkList;
286import com.android.metrics.NetworkRequestCount;
287import com.android.metrics.RequestCountForType;
Chiachang Wang62740142020-11-02 16:51:24 +0800288import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900289import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800290import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000291import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900292import com.android.net.module.util.BitUtils;
Junyu Lai155760b2023-10-05 14:51:00 +0800293import com.android.net.module.util.BpfUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900294import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900295import com.android.net.module.util.DeviceConfigUtils;
Junyu Lai2ff42d22023-12-07 16:57:13 +0800296import com.android.net.module.util.HandlerUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100297import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900298import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
299import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900300import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800301import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800302import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100303import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000304import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800305import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
306import com.android.networkstack.apishim.ConstantsShim;
307import com.android.networkstack.apishim.common.BroadcastOptionsShim;
308import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900309import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900310import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000311import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900312import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800313import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800314import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900315import com.android.server.connectivity.ConnectivityFlags;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900316import com.android.server.connectivity.ConnectivityResources;
Erik Kline32120082017-12-13 19:40:49 +0900317import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500318import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700319import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900320import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900321import com.android.server.connectivity.InvalidTagException;
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +0900322import com.android.server.connectivity.KeepaliveResourceUtil;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000323import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100324import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700325import com.android.server.connectivity.MockableSystemProperties;
Yang Sun29037f62023-12-04 10:31:58 +0800326import com.android.server.connectivity.MulticastRoutingCoordinatorService;
Chalard Jean43aae652022-09-14 21:33:06 +0900327import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700328import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600329import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900330import com.android.server.connectivity.NetworkNotificationManager;
331import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900332import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900333import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900334import com.android.server.connectivity.NetworkRanker;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000335import com.android.server.connectivity.NetworkRequestStateStatsMetrics;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700336import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900337import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900338import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700339import com.android.server.connectivity.QosCallbackTracker;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900340import com.android.server.connectivity.RoutingCoordinatorService;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000341import com.android.server.connectivity.SatelliteAccessController;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800342import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000343import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800344import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600345
Josh Gao461a1222020-06-16 15:58:11 -0700346import libcore.io.IoUtils;
347
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900348import org.xmlpull.v1.XmlPullParserException;
349
The Android Open Source Project28527d22009-03-03 19:31:44 -0800350import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100351import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900352import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800353import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900354import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700355import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700356import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900357import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900358import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700359import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700360import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700361import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700362import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800363import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900364import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800365import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700366import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700367import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700368import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700369import java.util.Map;
Yang Sun29037f62023-12-04 10:31:58 +0800370import java.util.Map.Entry;
Chalard Jean524f0b12021-10-25 21:11:56 +0900371import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700372import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900373import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600374import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900375import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600376import java.util.TreeSet;
Chalard Jeanf95e2de2023-08-22 19:07:47 +0900377import java.util.concurrent.TimeUnit;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900378import java.util.concurrent.atomic.AtomicInteger;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000379import java.util.function.Consumer;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800380
381/**
382 * @hide
383 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800384public class ConnectivityService extends IConnectivityManager.Stub
385 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900386 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800387
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900388 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900389 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900390 private static final String NETWORK_ARG = "networks";
391 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800392 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900393
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900394 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900395 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
396 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800397
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900398 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700399
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100400 /**
401 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
402 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800403 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100404 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
405 * (preferably via runtime resource overlays).
406 */
407 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
408 "http://connectivitycheck.gstatic.com/generate_204";
409
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700410 // TODO: create better separation between radio types and network types
411
Robert Greenwalt2034b912009-08-12 16:08:25 -0700412 // how long to wait before switching back to a radio's default network
413 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
414 // system property that can override the above value
415 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
416 "android.telephony.apn-restore";
417
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900418 // How long to wait before putting up a "This network doesn't have an Internet connection,
419 // connect anyway?" dialog after the user selects a network that doesn't validate.
420 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
421
Chalard Jean5fb43c72022-09-08 19:03:14 +0900422 // How long to wait before considering that a network is bad in the absence of any form
423 // of connectivity (valid, partial, captive portal). If none has been detected after this
424 // delay, the stack considers this network bad, which may affect how it's handled in ranking
425 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900426 // Timeout in case the "actively prefer bad wifi" feature is on
427 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
428 // Timeout in case the "actively prefer bad wifi" feature is off
Chalard Jean0f141332023-06-05 19:26:17 +0900429 private static final int DEFAULT_EVALUATION_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900430
junyulai0ac374f2020-12-14 18:41:52 +0800431 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900432 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
433 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800434 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700435
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800436 // Delimiter used when creating the broadcast delivery group for sending
437 // CONNECTIVITY_ACTION broadcast.
438 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
439
he_won.hwang881307a2022-03-15 21:23:52 +0900440 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900441 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900442
Daniel Brightf9e945b2020-06-15 16:10:01 -0700443 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900444 @VisibleForTesting
445 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700446
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900447 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700448 @VisibleForTesting
449 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900450
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900451 @VisibleForTesting
452 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800453 @VisibleForTesting
454 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900455 // True if the cell radio of the device is capable of time-sharing.
456 @VisibleForTesting
457 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900458
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800459 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800460 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800461 private final int mReleasePendingIntentDelayMs;
462
Chalard Jean46bfbf02022-02-02 00:56:25 +0900463 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900464
Motomu Utsumif360aa62023-01-30 17:52:20 +0900465 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700466
Chalard Jean9473c982021-07-29 20:03:04 +0900467 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800468 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700469 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800470 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700471
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900472 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700473
Ying Xu7cabd322024-01-15 18:40:15 -0800474 private final boolean mRequestRestrictedWifiEnabled;
475
junyulaif2c67e42018-08-07 19:50:45 +0800476 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000477 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
478 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800479 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900480 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800481
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900482 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900483 private final ConnectivityResources mResources;
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +0000484 private final int mWakeUpMark;
485 private final int mWakeUpMask;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000486 // The Context is created for UserHandle.ALL.
487 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900488 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900489 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700490 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700491 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800492
Chenbo Feng15416292018-11-08 17:36:21 -0800493 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800494 protected IDnsResolver mDnsResolver;
495 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800496 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700497 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900498 private final NetworkStatsManager mStatsManager;
499 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800500 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700501
Benedict Wong493e04b2018-11-09 14:45:34 -0800502 /**
503 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
504 * instances.
505 */
506 @GuardedBy("mTNSLock")
507 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800508 private final CompanionDeviceManagerProxyService mCdmps;
Yang Sun29037f62023-12-04 10:31:58 +0800509 private final MulticastRoutingCoordinatorService mMulticastRoutingCoordinatorService;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900510 private final RoutingCoordinatorService mRoutingCoordinatorService;
Benedict Wong493e04b2018-11-09 14:45:34 -0800511
512 private final Object mTNSLock = new Object();
513
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700514 private String mCurrentTcpBufferSizes;
515
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900516 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000517 new Class[] {
518 ConnectivityService.class,
519 NetworkAgent.class,
520 NetworkAgentInfo.class,
521 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900522
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500523 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400524 // Tear down networks that have no chance (e.g. even if validated) of becoming
525 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500526 // all networks have been rematched against all NetworkRequests.
527 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400528 // Don't reap networks. This should be passed when some networks have not yet been
529 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500530 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900531 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500532
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900533 private enum UnneededFor {
534 LINGER, // Determine whether this network is unneeded and should be lingered.
535 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
536 }
537
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700538 /**
paulhuaa0743d2021-05-26 21:56:03 +0800539 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800540 * should have priority. The order is passed to netd which will use it together
541 * with UID ranges to generate the corresponding IP rule. This serves to
542 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800543 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800544 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000545 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800546 *
paulhu48291862021-07-14 14:53:57 +0800547 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
548 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800549 */
paulhu48291862021-07-14 14:53:57 +0800550 // Used when sending to netd to code for "no order".
551 static final int PREFERENCE_ORDER_NONE = 0;
552 // Order for requests that don't code for a per-app preference. As it is
553 // out of the valid range, the corresponding order should be
554 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800555 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800556 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800557 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800558 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
559 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800560 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800561 static final int PREFERENCE_ORDER_OEM = 10;
562 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800563 // See {@link #setProfileNetworkPreference}.
564 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800565 static final int PREFERENCE_ORDER_PROFILE = 20;
566 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800567 // better scores are connected.
568 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800569 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800570 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000571 // Order of setting satellite network preference fallback when default message application
572 // with role_sms role and android.permission.SATELLITE_COMMUNICATION permission detected
573 @VisibleForTesting
574 static final int PREFERENCE_ORDER_SATELLITE_FALLBACK = 40;
Chalard Jeane6c95272022-01-25 21:04:21 +0900575 // Preference order that signifies the network shouldn't be set as a default network for
576 // the UIDs, only give them access to it. TODO : replace this with a boolean
577 // in NativeUidRangeConfig
578 @VisibleForTesting
579 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
580 // Bound for the lowest valid preference order.
581 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800582
583 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700584 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700585 * from one net to another. Clear happens when we get a new
586 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
587 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700588 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700589 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700590
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700591 /**
592 * used internally to reload global proxy settings
593 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700594 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700595
Robert Greenwalt34848c02011-03-25 13:09:25 -0700596 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400597 * PAC manager has received new port.
598 */
Aaron Huang9fe47be2021-06-08 13:11:45 +0800599 private static final int EVENT_PAC_PROXY_HAS_CHANGED = 16;
Jason Monka69f1b02013-10-10 14:02:51 -0400600
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700601 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900602 * used internally when registering NetworkProviders
603 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700604 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900605 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700606
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700607 /**
608 * used internally when registering NetworkAgents
609 * obj = Messenger
610 */
611 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
612
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700613 /**
614 * used to add a network request
615 * includes a NetworkRequestInfo
616 */
617 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
618
619 /**
620 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900621 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700622 * cancel it.
623 * includes a NetworkRequestInfo
624 */
625 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
626
627 /**
628 * used to add a network listener - no request
629 * includes a NetworkRequestInfo
630 */
631 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
632
633 /**
634 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400635 * arg1 = UID of caller
636 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700637 */
638 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
639
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700640 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900641 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700642 * obj = Messenger
643 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900644 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700645
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700646 /**
647 * used internally to expire a wakelock when transitioning
648 * from one net to another. Expire happens when we fail to find
649 * a new network (typically after 1 minute) -
650 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
651 * a replacement network.
652 */
653 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
654
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700655 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800656 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400657 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800658 */
659 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
660
661 /**
662 * used to remove a pending intent and its associated network request.
663 * arg1 = UID of caller
664 * obj = PendingIntent
665 */
666 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
667
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900668 /**
669 * used to specify whether a network should be used even if unvalidated.
670 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
671 * arg2 = whether to remember this choice in the future (1 or 0)
672 * obj = network
673 */
674 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
675
676 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700677 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900678 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700679 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900680
Paul Jensenc8873fc2015-06-17 14:15:39 -0400681 /**
682 * used to add a network listener with a pending intent
683 * obj = NetworkRequestInfo
684 */
685 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
686
Hugo Benichid6b510a2017-04-06 17:22:18 +0900687 /**
688 * used to specify whether a network should not be penalized when it becomes unvalidated.
689 */
690 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
691
692 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700693 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900694 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700695 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900696
Erik Kline31b4a9e2018-01-11 21:07:29 +0900697 // Handle changes in Private DNS settings.
698 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
699
dalyk1720e542018-03-05 12:42:22 -0500700 // Handle private DNS validation status updates.
701 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
702
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900703 /**
704 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
705 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800706 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
707 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
708 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900709 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900710 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900711
712 /**
713 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
714 * config was resolved.
715 * obj = PrivateDnsConfig
716 * arg2 = netid
717 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900718 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900719
720 /**
721 * Request ConnectivityService display provisioning notification.
722 * arg1 = Whether to make the notification visible.
723 * arg2 = NetID.
724 * obj = Intent to be launched when notification selected by user, null if !arg1.
725 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900726 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900727
728 /**
lucaslin2240ef62019-03-12 13:08:03 +0800729 * Used to specify whether a network should be used even if connectivity is partial.
730 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
731 * false)
732 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
733 * obj = network
734 */
lucaslin444d43a2020-02-20 16:56:59 +0800735 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800736
737 /**
lucasline117e2e2019-10-22 18:27:33 +0800738 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
739 * Both of the arguments are bitmasks, and the value of bits come from
740 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900741 * arg1 = unused
742 * arg2 = netId
743 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800744 */
lucaslin444d43a2020-02-20 16:56:59 +0800745 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800746
747 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900748 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
749 * arg1 = unused
750 * arg2 = netId
751 * obj = captive portal data
752 */
lucaslin444d43a2020-02-20 16:56:59 +0800753 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900754
755 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900756 * Used by setRequireVpnForUids.
757 * arg1 = whether the specified UID ranges are required to use a VPN.
758 * obj = Array of UidRange objects.
759 */
760 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
761
762 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900763 * Used internally when setting the default networks for OemNetworkPreferences.
764 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800765 */
766 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
767
768 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800769 * Used to indicate the system default network becomes active.
770 */
771 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
772
773 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900774 * Used internally when setting a network preference for a user profile.
775 * obj = Pair<ProfileNetworkPreference, Listener>
776 */
777 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
778
779 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000780 * Event to specify that reasons for why an uid is blocked changed.
781 * arg1 = uid
782 * arg2 = blockedReasons
783 */
784 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
785
786 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900787 * Event to register a new network offer
788 * obj = NetworkOffer
789 */
790 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
791
792 /**
793 * Event to unregister an existing network offer
794 * obj = INetworkOfferCallback
795 */
796 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
797
798 /**
paulhu51f77dc2021-06-07 02:34:20 +0000799 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
800 */
801 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
802
803 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800804 * Event to set temporary allow bad wifi within a limited time to override
805 * {@code config_networkAvoidBadWifi}.
806 */
807 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
808
809 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100810 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
811 */
812 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
813
814 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900815 * The initial evaluation period is over for this network.
816 *
817 * If no form of connectivity has been found on this network (valid, partial, captive portal)
818 * then the stack will now consider it to have been determined bad.
819 */
820 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
821
822 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000823 * Used internally when the user does not want the network from captive portal app.
824 * obj = Network
825 */
826 private static final int EVENT_USER_DOES_NOT_WANT = 58;
827
828 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000829 * Event to set VPN as preferred network for specific apps.
830 * obj = VpnNetworkPreferenceInfo
831 */
832 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
833
834 /**
chiachangwange0192a72023-02-06 13:25:01 +0000835 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
836 */
837 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
838
839 /**
Mark Fasheh7c999d82023-05-04 20:23:11 +0000840 * Event to inform the ConnectivityService handler when a uid has been frozen or unfrozen.
841 */
842 private static final int EVENT_UID_FROZEN_STATE_CHANGED = 61;
843
844 /**
Ying Xu7cabd322024-01-15 18:40:15 -0800845 * Event to inform the ConnectivityService handler when a uid has lost carrier privileges.
846 */
847 private static final int EVENT_UID_CARRIER_PRIVILEGES_LOST = 62;
848
849 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900850 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
851 * should be shown.
852 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900853 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900854
855 /**
856 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
857 * should be hidden.
858 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900859 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900860
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800861 /**
862 * The maximum alive time to allow bad wifi configuration for testing.
863 */
864 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
865
Patrick Rohr2857ac42022-01-21 14:58:16 +0100866 /**
chiachangwange0192a72023-02-06 13:25:01 +0000867 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
868 * testing.
869 */
870 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
871
872 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100873 * The priority of the tc police rate limiter -- smaller value is higher priority.
874 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
875 */
876 private static final short TC_PRIO_POLICE = 1;
877
878 /**
879 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
880 */
881 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700882 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100883
Hugo Benichi47011212017-03-30 10:46:05 +0900884 private static String eventName(int what) {
885 return sMagicDecoderRing.get(what, Integer.toString(what));
886 }
887
paulhua10d8212020-11-10 15:32:56 +0800888 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900889 final DnsResolverServiceManager dsm = context.getSystemService(
890 DnsResolverServiceManager.class);
891 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800892 }
893
Cody Kesting73708bf2019-12-18 10:57:50 -0800894 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900895 @VisibleForTesting
896 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700897 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700898 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700899 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700900 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800901 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
902 @VisibleForTesting
903 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
904
Erik Kline32120082017-12-13 19:40:49 +0900905 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900906 @VisibleForTesting
907 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700908
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400909 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800910 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400911
Chalard Jean46bfbf02022-02-02 00:56:25 +0900912 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800913 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700914
Chalard Jean5d70ba42018-06-07 16:44:04 +0900915 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
916 // the world when it changes.
Aaron Huang40b52442021-06-08 04:34:24 +0800917 private final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400918
Erik Kline05f2b402015-04-30 12:58:40 +0900919 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700920
Chalard Jean46bfbf02022-02-02 00:56:25 +0900921 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400922
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700923 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900924 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700925
Valentin Iftime9fa35092019-09-24 13:32:13 +0200926 private Set<String> mWolSupportedInterfaces;
927
Roshan Pius08c94fb2020-01-16 12:17:17 -0800928 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800929 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800930 private final AppOpsManager mAppOpsManager;
931
932 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400933
chiachangwang3d60bac2023-01-17 14:38:08 +0000934 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900935 private final QosCallbackTracker mQosCallbackTracker;
936 private final NetworkNotificationManager mNotifier;
937 private final LingerMonitor mLingerMonitor;
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +0000938 private final SatelliteAccessController mSatelliteAccessController;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900939
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700940 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800941 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700942
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900943 // Sequence number for NetworkProvider IDs.
944 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
945 NetworkProvider.FIRST_PROVIDER_ID);
946
Erik Klineedf878b2015-07-09 18:24:03 +0900947 // NetworkRequest activity String log entries.
948 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
949 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
950
Hugo Benichid159fdd2016-07-11 11:05:12 +0900951 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900952 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900953 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
954
Hugo Benichi47011212017-03-30 10:46:05 +0900955 private static final int MAX_WAKELOCK_LOGS = 20;
956 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900957 private int mTotalWakelockAcquisitions = 0;
958 private int mTotalWakelockReleases = 0;
959 private long mTotalWakelockDurationMs = 0;
960 private long mMaxWakelockDurationMs = 0;
961 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900962
Hugo Benichi208c0102016-07-28 17:53:06 +0900963 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900964
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +0000965 @Nullable private final NetworkRequestStateStatsMetrics mNetworkRequestStateStatsMetrics;
966
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700967 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900968 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700969
Erik Kline95ecfee2016-10-02 18:02:14 +0900970 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900971 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900972
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900973 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800974 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
975 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800976
Patrick Rohr2857ac42022-01-21 14:58:16 +0100977 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
978 // configured via {@link
979 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
980 // Only the handler thread is allowed to access this field.
981 private long mIngressRateLimit = -1;
982
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900983 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
984 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900985 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900986 @GuardedBy("mSelfCertifiedCapabilityCache")
987 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
988 mSelfCertifiedCapabilityCache = new HashMap<>();
989
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900990 // Flag to enable the feature of closing frozen app sockets.
991 private final boolean mDestroyFrozenSockets;
992
993 // Flag to optimize closing frozen app sockets by waiting for the cellular modem to wake up.
994 private final boolean mDelayDestroyFrozenSockets;
995
Quang Anh Luong28eefef2023-11-07 09:43:41 +0900996 // Flag to allow SysUI to receive connectivity reports for wifi picker UI.
997 private final boolean mAllowSysUiConnectivityReports;
998
Motomu Utsumi188bfd32023-05-30 14:38:04 +0900999 // Uids that ConnectivityService is pending to close sockets of.
1000 private final Set<Integer> mPendingFrozenUids = new ArraySet<>();
1001
Robert Greenwalt802c1102014-06-02 15:32:02 -07001002 /**
1003 * Implements support for the legacy "one network per network type" model.
1004 *
1005 * We used to have a static array of NetworkStateTrackers, one for each
1006 * network type, but that doesn't work any more now that we can have,
1007 * for example, more that one wifi network. This class stores all the
1008 * NetworkAgentInfo objects that support a given type, but the legacy
1009 * API will only see the first one.
1010 *
1011 * It serves two main purposes:
1012 *
1013 * 1. Provide information about "the network for a given type" (since this
1014 * API only supports one).
1015 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
1016 * the first network for a given type changes, or if the default network
1017 * changes.
1018 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001019 @VisibleForTesting
1020 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001021
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09001022 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001023 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001024
Robert Greenwalt802c1102014-06-02 15:32:02 -07001025 /**
1026 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
1027 * Each list holds references to all NetworkAgentInfos that are used to
1028 * satisfy requests for that network type.
1029 *
1030 * This array is built out at startup such that an unsupported network
1031 * doesn't get an ArrayList instance, making this a tristate:
1032 * unsupported, supported but not active and active.
1033 *
1034 * The actual lists are populated when we scan the network types that
1035 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +09001036 *
1037 * Threading model:
1038 * - addSupportedType() is only called in the constructor
1039 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
1040 * They are therefore not thread-safe with respect to each other.
1041 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
1042 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001043 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +09001044 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -07001045 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001046 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001047 @NonNull
1048 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001049
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001050 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
1051 // an entry have no timer (equivalent to -1). Lazily loaded.
1052 @NonNull
1053 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
1054
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001055 LegacyTypeTracker(@NonNull ConnectivityService service) {
1056 mService = service;
1057 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -07001058 }
1059
Chiachang Wang3bc52762021-11-25 14:17:57 +08001060 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
1061 // addressed.
1062 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001063 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
1064 final PackageManager pm = ctx.getPackageManager();
1065 if (pm.hasSystemFeature(FEATURE_WIFI)) {
1066 addSupportedType(TYPE_WIFI);
1067 }
1068 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
1069 addSupportedType(TYPE_WIFI_P2P);
1070 }
1071 if (tm.isDataCapable()) {
1072 // Telephony does not have granular support for these types: they are either all
1073 // supported, or none is supported
1074 addSupportedType(TYPE_MOBILE);
1075 addSupportedType(TYPE_MOBILE_MMS);
1076 addSupportedType(TYPE_MOBILE_SUPL);
1077 addSupportedType(TYPE_MOBILE_DUN);
1078 addSupportedType(TYPE_MOBILE_HIPRI);
1079 addSupportedType(TYPE_MOBILE_FOTA);
1080 addSupportedType(TYPE_MOBILE_IMS);
1081 addSupportedType(TYPE_MOBILE_CBS);
1082 addSupportedType(TYPE_MOBILE_IA);
1083 addSupportedType(TYPE_MOBILE_EMERGENCY);
1084 }
1085 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1086 addSupportedType(TYPE_BLUETOOTH);
1087 }
1088 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1089 // TYPE_PROXY is only used on Wear
1090 addSupportedType(TYPE_PROXY);
1091 }
1092 // Ethernet is often not specified in the configs, although many devices can use it via
1093 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001094 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001095 addSupportedType(TYPE_ETHERNET);
1096 }
1097
1098 // Always add TYPE_VPN as a supported type
1099 addSupportedType(TYPE_VPN);
1100 }
1101
1102 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001103 if (mTypeLists[type] != null) {
1104 throw new IllegalStateException(
1105 "legacy list for type " + type + "already initialized");
1106 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001107 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001108 }
1109
Robert Greenwalt802c1102014-06-02 15:32:02 -07001110 public boolean isTypeSupported(int type) {
1111 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1112 }
1113
1114 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001115 synchronized (mTypeLists) {
1116 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1117 return mTypeLists[type].get(0);
1118 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001119 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001120 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001121 }
1122
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001123 public int getRestoreTimerForType(int type) {
1124 synchronized (mTypeLists) {
1125 if (mRestoreTimers == null) {
1126 mRestoreTimers = loadRestoreTimers();
1127 }
1128 return mRestoreTimers.getOrDefault(type, -1);
1129 }
1130 }
1131
1132 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1133 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001134 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001135 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1136 for (final String config : configs) {
1137 final String[] splits = TextUtils.split(config, ",");
1138 if (splits.length != 2) {
1139 logwtf("Invalid restore timer token count: " + config);
1140 continue;
1141 }
1142 try {
1143 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1144 } catch (NumberFormatException e) {
1145 logwtf("Invalid restore timer number format: " + config, e);
1146 }
1147 }
1148 return ret;
1149 }
1150
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001151 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001152 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001153 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001154 log("Sending " + state
1155 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001156 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001157 }
1158 }
1159
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001160 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1161 // network type, to preserve previous behaviour.
1162 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1163 if (vpnNai != mService.getLegacyLockdownNai()) return;
1164
1165 if (vpnNai.declaredUnderlyingNetworks == null
1166 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1167 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1168 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1169 return;
1170 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001171 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001172 vpnNai.declaredUnderlyingNetworks[0]);
1173 if (underlyingNai == null) return;
1174
1175 final int type = underlyingNai.networkInfo.getType();
1176 final DetailedState state = DetailedState.CONNECTED;
1177 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1178 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1179 }
1180
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001181 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001182 public void add(int type, NetworkAgentInfo nai) {
1183 if (!isTypeSupported(type)) {
1184 return; // Invalid network type.
1185 }
1186 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1187
1188 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1189 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001190 return;
1191 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001192 synchronized (mTypeLists) {
1193 list.add(nai);
1194 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001195
Chalard Jean5b409c72021-02-04 13:12:59 +09001196 // Send a broadcast if this is the first network of its type or if it's the default.
1197 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001198
1199 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1200 // to preserve previous behaviour.
1201 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001202 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001203 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1204 mService.sendLegacyNetworkBroadcast(nai, state, type);
1205 }
1206
1207 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1208 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001209 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001210 }
1211
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001212 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001213 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001214 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1215 if (list == null || list.isEmpty()) {
1216 return;
1217 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001218 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001219
Hugo Benichi389633f2016-06-21 09:48:07 +09001220 synchronized (mTypeLists) {
1221 if (!list.remove(nai)) {
1222 return;
1223 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001224 }
1225
Lorenzo Colitti49767722015-05-01 00:30:10 +09001226 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001227 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1228 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001229 }
1230
1231 if (!list.isEmpty() && wasFirstNetwork) {
1232 if (DBG) log("Other network available for type " + type +
1233 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001234 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001235 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001236 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001237 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001238 }
1239 }
1240
1241 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001242 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1243 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001244 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001245 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001246 }
1247 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001248
Chalard Jean46bfbf02022-02-02 00:56:25 +09001249 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001250 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001251 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001252 final DetailedState state = nai.networkInfo.getDetailedState();
1253 for (int type = 0; type < mTypeLists.length; type++) {
1254 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001255 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001256 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001257 if (isFirst || contains && isDefault) {
1258 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001259 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001260 }
1261 }
1262 }
1263
Robert Greenwalt94e22142014-07-30 16:31:24 -07001264 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001265 pw.println("mLegacyTypeTracker:");
1266 pw.increaseIndent();
1267 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001268 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001269 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001270 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001271 pw.println();
1272 pw.println("Current state:");
1273 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001274 synchronized (mTypeLists) {
1275 for (int type = 0; type < mTypeLists.length; type++) {
1276 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1277 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001278 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001279 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001280 }
1281 }
1282 pw.decreaseIndent();
1283 pw.decreaseIndent();
1284 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001285 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001286 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001287 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001288
Ying Xu7cabd322024-01-15 18:40:15 -08001289 private final CarrierPrivilegesLostListenerImpl mCarrierPrivilegesLostListenerImpl =
1290 new CarrierPrivilegesLostListenerImpl();
1291
1292 private class CarrierPrivilegesLostListenerImpl implements CarrierPrivilegesLostListener {
1293 @Override
1294 public void onCarrierPrivilegesLost(int uid) {
1295 if (mRequestRestrictedWifiEnabled) {
1296 mHandler.sendMessage(mHandler.obtainMessage(
1297 EVENT_UID_CARRIER_PRIVILEGES_LOST, uid, 0 /* arg2 */));
1298 }
1299 }
1300 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001301 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001302 /**
1303 * Helper class which parses out priority arguments and dumps sections according to their
1304 * priority. If priority arguments are omitted, function calls the legacy dump command.
1305 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001306 private class LocalPriorityDump {
1307 private static final String PRIORITY_ARG = "--dump-priority";
1308 private static final String PRIORITY_ARG_HIGH = "HIGH";
1309 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
Junyu Laif8dba342023-10-12 17:01:03 +08001310 private static final int DUMPSYS_DEFAULT_TIMEOUT_MS = 10_000;
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001311
1312 LocalPriorityDump() {}
1313
1314 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001315 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> {
Junyu Laif8dba342023-10-12 17:01:03 +08001316 doDump(fd, pw, new String[]{DIAG_ARG});
1317 doDump(fd, pw, new String[]{SHORT_ARG});
1318 }, DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1319 pw.println("dumpHigh timeout");
1320 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001321 }
1322
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001323 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
Junyu Lai2ff42d22023-12-07 16:57:13 +08001324 if (!HandlerUtils.runWithScissorsForDump(mHandler, () -> doDump(fd, pw, args),
Junyu Laif8dba342023-10-12 17:01:03 +08001325 DUMPSYS_DEFAULT_TIMEOUT_MS)) {
1326 pw.println("dumpNormal timeout");
1327 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001328 }
1329
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001330 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1331 if (args == null) {
1332 dumpNormal(fd, pw, args);
1333 return;
1334 }
1335
1336 String priority = null;
1337 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1338 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1339 argIndex++;
1340 priority = args[argIndex];
1341 }
1342 }
1343
1344 if (PRIORITY_ARG_HIGH.equals(priority)) {
1345 dumpHigh(fd, pw);
1346 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1347 dumpNormal(fd, pw, args);
1348 } else {
1349 // ConnectivityService publishes binder service using publishBinderService() with
1350 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001351 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1352 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001353 // TODO: Integrate into signal dump.
1354 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001355 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001356 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001357 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001358
Ying Xu7cabd322024-01-15 18:40:15 -08001359 @VisibleForTesting
1360 CarrierPrivilegesLostListener getCarrierPrivilegesLostListener() {
1361 return mCarrierPrivilegesLostListenerImpl;
1362 }
1363
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001364 /**
1365 * Dependencies of ConnectivityService, for injection in tests.
1366 */
1367 @VisibleForTesting
1368 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001369 public int getCallingUid() {
1370 return Binder.getCallingUid();
1371 }
1372
Chalard Jeandf29a852023-05-29 17:02:43 +09001373 public boolean isAtLeastS() {
1374 return SdkLevel.isAtLeastS();
1375 }
1376
1377 public boolean isAtLeastT() {
1378 return SdkLevel.isAtLeastT();
1379 }
1380
1381 public boolean isAtLeastU() {
1382 return SdkLevel.isAtLeastU();
1383 }
1384
Chalard Jeaneb663892023-10-07 15:17:07 +09001385 public boolean isAtLeastV() {
1386 return SdkLevel.isAtLeastV();
1387 }
1388
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001389 /**
1390 * Get system properties to use in ConnectivityService.
1391 */
1392 public MockableSystemProperties getSystemProperties() {
1393 return new MockableSystemProperties();
1394 }
1395
1396 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001397 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1398 */
1399 public ConnectivityResources getResources(@NonNull Context ctx) {
1400 return new ConnectivityResources(ctx);
1401 }
1402
1403 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001404 * Create a HandlerThread to use in ConnectivityService.
1405 */
Chalard Jean96ff9542023-11-02 14:24:47 +09001406 public HandlerThread makeHandlerThread(@NonNull final String tag) {
1407 return new HandlerThread(tag);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001408 }
1409
1410 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001411 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001412 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001413 public NetworkStackClientBase getNetworkStack() {
1414 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001415 }
1416
1417 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001418 * @see ProxyTracker
1419 */
1420 public ProxyTracker makeProxyTracker(@NonNull Context context,
1421 @NonNull Handler connServiceHandler) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08001422 return new ProxyTracker(context, connServiceHandler, EVENT_PAC_PROXY_HAS_CHANGED);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001423 }
1424
1425 /**
1426 * @see NetIdManager
1427 */
1428 public NetIdManager makeNetIdManager() {
1429 return new NetIdManager();
1430 }
1431
1432 /**
1433 * @see NetworkUtils#queryUserAccess(int, int)
1434 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001435 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1436 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001437 }
1438
1439 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001440 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1441 * requires CAP_NET_ADMIN, which the unit tests do not have.
1442 */
1443 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1444 InetSocketAddress remote) {
1445 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1446 }
1447
1448 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001449 * @see MultinetworkPolicyTracker
1450 */
1451 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1452 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1453 return new MultinetworkPolicyTracker(c, h, r);
1454 }
1455
Aaron Huang330a4c02020-10-27 03:36:19 +08001456 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001457 * @see AutomaticOnOffKeepaliveTracker
1458 */
1459 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1460 @NonNull Context c, @NonNull Handler h) {
1461 return new AutomaticOnOffKeepaliveTracker(c, h);
1462 }
1463
Yang Sun29037f62023-12-04 10:31:58 +08001464 public MulticastRoutingCoordinatorService makeMulticastRoutingCoordinatorService(
1465 @NonNull Handler h) {
1466 try {
1467 return new MulticastRoutingCoordinatorService(h);
1468 } catch (UnsupportedOperationException e) {
1469 // Multicast routing is not supported by the kernel
1470 Log.i(TAG, "Skipping unsupported MulticastRoutingCoordinatorService");
1471 return null;
1472 }
1473 }
1474
chiachangwang7c17c282023-02-02 05:58:59 +00001475 /**
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001476 * @see NetworkRequestStateStatsMetrics
1477 */
1478 public NetworkRequestStateStatsMetrics makeNetworkRequestStateStatsMetrics(
1479 Context context) {
1480 // We currently have network requests metric for Watch devices only
1481 if (context.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
1482 return new NetworkRequestStateStatsMetrics();
1483 } else {
1484 return null;
1485 }
1486 }
1487
1488 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001489 * @see BatteryStatsManager
1490 */
1491 public void reportNetworkInterfaceForTransports(Context context, String iface,
1492 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001493 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001494 context.getSystemService(BatteryStatsManager.class);
1495 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1496 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001497
1498 public boolean getCellular464XlatEnabled() {
1499 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1500 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001501
1502 /**
1503 * @see PendingIntent#intentFilterEquals
1504 */
1505 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1506 return a.intentFilterEquals(b);
1507 }
1508
1509 /**
1510 * @see LocationPermissionChecker
1511 */
1512 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1513 return new LocationPermissionChecker(context);
1514 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001515
1516 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001517 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001518 *
1519 * This method returns null in versions before T, where carrier privilege
1520 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001521 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001522 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001523 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
Ying Xu7cabd322024-01-15 18:40:15 -08001524 @NonNull final Context context,
1525 @NonNull final TelephonyManager tm,
1526 boolean requestRestrictedWifiEnabled,
1527 @NonNull CarrierPrivilegesLostListener listener) {
Chalard Jeandf29a852023-05-29 17:02:43 +09001528 if (isAtLeastT()) {
Ying Xu7cabd322024-01-15 18:40:15 -08001529 return new CarrierPrivilegeAuthenticator(
1530 context, tm, requestRestrictedWifiEnabled, listener);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001531 } else {
1532 return null;
1533 }
1534 }
1535
1536 /**
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00001537 * @see SatelliteAccessController
1538 */
1539 @Nullable
1540 public SatelliteAccessController makeSatelliteAccessController(
1541 @NonNull final Context context,
1542 Consumer<Set<Integer>> updateSatelliteNetworkFallbackUidCallback,
1543 @NonNull final Handler connectivityServiceInternalHandler) {
1544 return new SatelliteAccessController(context, updateSatelliteNetworkFallbackUidCallback,
1545 connectivityServiceInternalHandler);
1546 }
1547
1548 /**
Motomu Utsumi624aeb42023-08-15 15:52:27 +09001549 * @see DeviceConfigUtils#isTetheringFeatureEnabled
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001550 */
Motomu Utsumi278db582023-04-21 12:35:22 +09001551 public boolean isFeatureEnabled(Context context, String name) {
Motomu Utsumi3e0be392023-08-15 16:32:44 +09001552 return DeviceConfigUtils.isTetheringFeatureEnabled(context, name);
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001553 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001554
1555 /**
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001556 * @see DeviceConfigUtils#isTetheringFeatureNotChickenedOut
1557 */
1558 public boolean isFeatureNotChickenedOut(Context context, String name) {
1559 return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context, name);
1560 }
1561
1562 /**
Wayne Ma2fde98c2022-01-17 18:04:05 +08001563 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001564 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001565 * @return BpfNetMaps implementation.
1566 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001567 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1568 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001569 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001570
1571 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001572 * @see ClatCoordinator
1573 */
Maciej Żenczykowski7b059872023-06-08 18:50:41 -07001574 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001575 public ClatCoordinator getClatCoordinator(INetd netd) {
1576 return new ClatCoordinator(
1577 new ClatCoordinator.Dependencies() {
1578 @NonNull
1579 public INetd getNetd() {
1580 return netd;
1581 }
1582 });
1583 }
1584
1585 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001586 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1587 */
1588 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1589 final InterfaceParams params = InterfaceParams.getByName(iface);
1590 if (params == null) {
1591 // the interface might have disappeared.
1592 logw("Failed to get interface params for interface " + iface);
1593 return;
1594 }
1595 try {
1596 // converting rateInBytesPerSecond from long to int is safe here because the
1597 // setting's range is limited to INT_MAX.
1598 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001599 Log.i(TAG,
1600 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001601 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1602 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1603 } catch (IOException e) {
1604 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1605 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1606 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1607 + ") failure: ", e);
1608 }
1609 }
1610
1611 /**
1612 * Wraps {@link TcUtils#tcFilterDelDev}
1613 */
1614 public void disableIngressRateLimit(String iface) {
1615 final InterfaceParams params = InterfaceParams.getByName(iface);
1616 if (params == null) {
1617 // the interface might have disappeared.
1618 logw("Failed to get interface params for interface " + iface);
1619 return;
1620 }
1621 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001622 Log.i(TAG,
1623 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001624 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1625 } catch (IOException e) {
1626 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1627 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1628 }
1629 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001630
1631 /**
Junyu Lai155760b2023-10-05 14:51:00 +08001632 * Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
1633 */
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001634 public int getBpfProgramId(final int attachType)
Junyu Lai155760b2023-10-05 14:51:00 +08001635 throws IOException {
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00001636 return BpfUtils.getProgramId(attachType);
Junyu Lai155760b2023-10-05 14:51:00 +08001637 }
1638
1639 /**
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001640 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1641 */
1642 // TODO: when available in all active branches:
1643 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1644 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1645 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1646 return BroadcastOptionsShimImpl.newInstance(options);
1647 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001648
1649 /**
1650 * Wrapper method for
1651 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1652 *
1653 * @param changeId The ID of the compatibility change in question.
1654 * @param packageName The package name of the app in question.
1655 * @param user The user that the operation is done for.
1656 * @return {@code true} if the change is enabled for the specified package.
1657 */
1658 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1659 @NonNull final UserHandle user) {
1660 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1661 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001662
1663 /**
Chalard Jeandf29a852023-05-29 17:02:43 +09001664 * As above but with a UID.
1665 * @see CompatChanges#isChangeEnabled(long, int)
1666 */
1667 public boolean isChangeEnabled(final long changeId, final int uid) {
1668 return CompatChanges.isChangeEnabled(changeId, uid);
1669 }
1670
1671 /**
Motomu Utsumi93a22182023-03-16 17:04:21 +09001672 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1673 *
1674 * @param ranges target uid ranges
1675 * @param exemptUids uids to skip close socket
1676 */
1677 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1678 @NonNull final Set<Integer> exemptUids)
1679 throws SocketException, InterruptedIOException, ErrnoException {
1680 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1681 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +09001682
1683 /**
1684 * Call {@link InetDiagMessage#destroyLiveTcpSocketsByOwnerUids(Set)}
1685 *
1686 * @param ownerUids target uids to close sockets
1687 */
1688 public void destroyLiveTcpSocketsByOwnerUids(final Set<Integer> ownerUids)
1689 throws SocketException, InterruptedIOException, ErrnoException {
1690 InetDiagMessage.destroyLiveTcpSocketsByOwnerUids(ownerUids);
1691 }
Chalard Jean6f6c3532023-05-15 17:26:13 +09001692
1693 /**
1694 * Schedule the evaluation timeout.
1695 *
1696 * When a network connects, it's "not evaluated" yet. Detection events cause the network
1697 * to be "evaluated" (typically, validation or detection of a captive portal). If none
1698 * of these events happen, this time will run out, after which the network is considered
1699 * "evaluated" even if nothing happened to it. Notionally that means the system gave up
1700 * on this network and considers it won't provide connectivity. In particular, that means
1701 * it's when the system prefers it to cell if it's wifi and configuration says it should
1702 * prefer bad wifi to cell.
1703 */
1704 public void scheduleEvaluationTimeout(@NonNull Handler handler,
1705 @NonNull final Network network, final long delayMs) {
1706 handler.sendMessageDelayed(
1707 handler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
1708 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001709 }
1710
junyulaie7c7d2a2021-01-26 15:29:15 +08001711 public ConnectivityService(Context context) {
1712 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001713 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1714 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001715 }
1716
1717 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001718 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1719 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001720 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001721
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001722 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001723 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001724 mSystemProperties = mDeps.getSystemProperties();
1725 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001726 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001727 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001728 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1729 // Pass limit - 1 to maintain backward compatibility.
1730 // TODO: Remove the workaround.
1731 mNetworkRequestCounter =
1732 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1733 mSystemNetworkRequestCounter =
1734 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001735
Hugo Benichi208c0102016-07-28 17:53:06 +09001736 mMetricsLog = logger;
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00001737 mNetworkRequestStateStatsMetrics = mDeps.makeNetworkRequestStateStatsMetrics(mContext);
James Mattis45d81842021-01-10 14:24:24 -08001738 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1739 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001740 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001741 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001742 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001743 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1744 mDefaultNetworkRequests.add(mDefaultRequest);
1745 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001746
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001747 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001748 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001749
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001750 // The default WiFi request is a background request so that apps using WiFi are
1751 // migrated to a better network (typically ethernet) when one comes up, instead
1752 // of staying on WiFi forever.
1753 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1754 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1755
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001756 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1757 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1758 NetworkRequest.Type.BACKGROUND_REQUEST);
1759
Chalard Jean0702f982021-09-16 21:50:07 +09001760 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1761 // TODO: Consider making the timer customizable.
1762 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1763 mCellularRadioTimesharingCapable =
1764 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1765
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00001766 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
1767 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
1768
1769 if (SdkLevel.isAtLeastU()) {
1770 // U+ default value of both mark & mask, this is the top bit of the skb->mark,
1771 // see //system/netd/include/FwMark.h union Fwmark, field ingress_cpu_wakeup
1772 final int defaultUMarkMask = 0x80000000; // u32
1773
1774 if ((mark == 0) || (mask == 0)) {
1775 // simply treat unset/disabled as the default U value
1776 mark = defaultUMarkMask;
1777 mask = defaultUMarkMask;
1778 }
1779 if ((mark != defaultUMarkMask) || (mask != defaultUMarkMask)) {
1780 // invalid device overlay settings
1781 throw new IllegalArgumentException(
1782 "Bad config_networkWakeupPacketMark/Mask " + mark + "/" + mask);
1783 }
1784 }
1785
1786 mWakeUpMark = mark;
1787 mWakeUpMask = mask;
1788
Paul Hu51f816b2022-08-11 14:43:47 +00001789 mNetd = netd;
1790 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Chalard Jean96ff9542023-11-02 14:24:47 +09001791 mHandlerThread = mDeps.makeHandlerThread("ConnectivityServiceThread");
Paul Hu51f816b2022-08-11 14:43:47 +00001792 mPermissionMonitor =
1793 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001794 mHandlerThread.start();
1795 mHandler = new InternalHandler(mHandlerThread.getLooper());
1796 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001797 mConnectivityDiagnosticsHandler =
1798 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001799
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001800 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001801 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001802
junyulaie7c7d2a2021-01-26 15:29:15 +08001803 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001804 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001805 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001806 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001807
Wink Saville32506bc2013-06-29 21:10:57 -07001808 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001809 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001810 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Ying Xu7cabd322024-01-15 18:40:15 -08001811 mRequestRestrictedWifiEnabled = mDeps.isAtLeastU()
1812 && mDeps.isFeatureEnabled(context, REQUEST_RESTRICTED_WIFI);
1813 mCarrierPrivilegeAuthenticator = mDeps.makeCarrierPrivilegeAuthenticator(
1814 mContext, mTelephonyManager, mRequestRestrictedWifiEnabled,
1815 mCarrierPrivilegesLostListenerImpl);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001816
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00001817 if (mDeps.isAtLeastU()
1818 && mDeps
1819 .isFeatureNotChickenedOut(mContext, ALLOW_SATALLITE_NETWORK_FALLBACK)) {
1820 mSatelliteAccessController = mDeps.makeSatelliteAccessController(
1821 mContext, this::updateSatelliteNetworkPreferenceUids, mHandler);
1822 } else {
1823 mSatelliteAccessController = null;
1824 }
1825
Sudheer Shanka9967d462021-03-18 19:09:25 +00001826 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001827 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1828 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001829 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001830
1831 final PowerManager powerManager = (PowerManager) context.getSystemService(
1832 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001833 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001834 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001835
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001836 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1837 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001838 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001839 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001840 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001841 mProtectedNetworks.add(p);
1842 } else {
1843 if (DBG) loge("Ignoring protectedNetwork " + p);
1844 }
1845 }
1846
soma, kawata29444ae2019-05-23 09:30:40 +09001847 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1848
James Mattis02220e22021-03-13 19:27:21 -08001849 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001850 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001851 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001852 final IntentFilter userIntentFilter = new IntentFilter();
1853 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1854 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1855 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1856 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001857
James Mattis02220e22021-03-13 19:27:21 -08001858 // Listen to package add/removes for netd
1859 final IntentFilter packageIntentFilter = new IntentFilter();
1860 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1861 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1862 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1863 packageIntentFilter.addDataScheme("package");
1864 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001865 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001866
Junyu Lai38c75032023-12-04 07:52:19 +00001867 // This is needed for pre-V devices to propagate the data saver status
1868 // to the BPF map. This isn't supported before Android T because BPF maps are
1869 // unsupported, and it's also unnecessary on Android V and later versions,
1870 // as the platform code handles data saver bit updates. Additionally, checking
1871 // the initial data saver status here is superfluous because the intent won't
1872 // be sent until the system is ready.
1873 if (mDeps.isAtLeastT() && !mDeps.isAtLeastV()) {
1874 final IntentFilter dataSaverIntentFilter =
1875 new IntentFilter(ACTION_RESTRICT_BACKGROUND_CHANGED);
1876 mUserAllContext.registerReceiver(mDataSaverReceiver, dataSaverIntentFilter,
1877 null /* broadcastPermission */, mHandler);
1878 }
1879
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09001880 // TrackMultiNetworkActivities feature should be enabled by trunk stable flag.
1881 // But reading the trunk stable flags from mainline modules is not supported yet.
1882 // So enabling this feature on V+ release.
1883 mTrackMultiNetworkActivities = mDeps.isAtLeastV();
1884 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mNetd, mHandler,
1885 mTrackMultiNetworkActivities);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001886
Chalard Jean46bfbf02022-02-02 00:56:25 +09001887 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001888 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001889 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001890 } catch (RemoteException | ServiceSpecificException e) {
1891 loge("Error registering event listener :" + e);
1892 }
1893
Erik Kline05f2b402015-04-30 12:58:40 +09001894 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1895 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001896
chiachangwang7c17c282023-02-02 05:58:59 +00001897 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001898 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001899 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001900
1901 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001902 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001903 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1904 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001905 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001906 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1907 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001908
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001909 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001910 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001911 mNetworkRanker =
1912 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1913
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001914 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001915
Chiachang Wangc1215d32020-10-20 15:38:58 +08001916 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001917 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001918
Chalard Jean28018572020-12-21 18:36:52 +09001919 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1920 // request that doesn't allow fallback to the default network. It should never be visible
1921 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1922 // arguments like the handler or the DnsResolver.
1923 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001924 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001925 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001926 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09001927 new LinkProperties(), new NetworkCapabilities(), null /* localNetworkConfig */,
Chalard Jean28018572020-12-21 18:36:52 +09001928 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001929 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1930 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001931
1932 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001933 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1934 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1935 // Even if it could, running on S would at least require mocking out the BPF map,
1936 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1937 // the bpf syscall. http://aosp/1907693
Chalard Jeandf29a852023-05-29 17:02:43 +09001938 if (mDeps.isAtLeastT()) {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001939 mDscpPolicyTracker = new DscpPolicyTracker();
1940 }
Tyler Wear72388212021-09-09 14:49:02 -07001941 } catch (ErrnoException e) {
1942 loge("Unable to create DscpPolicyTracker");
1943 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001944
1945 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1946 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001947
Chalard Jeandf29a852023-05-29 17:02:43 +09001948 if (mDeps.isAtLeastT()) {
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001949 mCdmps = new CompanionDeviceManagerProxyService(context);
1950 } else {
1951 mCdmps = null;
1952 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00001953
Chalard Jean2fb66f12023-08-25 12:50:37 +09001954 mRoutingCoordinatorService = new RoutingCoordinatorService(netd);
Yang Sun29037f62023-12-04 10:31:58 +08001955 mMulticastRoutingCoordinatorService =
1956 mDeps.makeMulticastRoutingCoordinatorService(mHandler);
Chalard Jean2fb66f12023-08-25 12:50:37 +09001957
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001958 mDestroyFrozenSockets = mDeps.isAtLeastU()
1959 && mDeps.isFeatureEnabled(context, KEY_DESTROY_FROZEN_SOCKETS_VERSION);
1960 mDelayDestroyFrozenSockets = mDeps.isAtLeastU()
1961 && mDeps.isFeatureEnabled(context, DELAY_DESTROY_FROZEN_SOCKETS_VERSION);
Quang Anh Luong28eefef2023-11-07 09:43:41 +09001962 mAllowSysUiConnectivityReports = mDeps.isFeatureNotChickenedOut(
1963 mContext, ALLOW_SYSUI_CONNECTIVITY_REPORTS);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09001964 if (mDestroyFrozenSockets) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00001965 final UidFrozenStateChangedCallback frozenStateChangedCallback =
1966 new UidFrozenStateChangedCallback() {
1967 @Override
1968 public void onUidFrozenStateChanged(int[] uids, int[] frozenStates) {
1969 if (uids.length != frozenStates.length) {
1970 Log.wtf(TAG, "uids has length " + uids.length
1971 + " but frozenStates has length " + frozenStates.length);
1972 return;
1973 }
1974
1975 final UidFrozenStateChangedArgs args =
1976 new UidFrozenStateChangedArgs(uids, frozenStates);
1977
1978 mHandler.sendMessage(
1979 mHandler.obtainMessage(EVENT_UID_FROZEN_STATE_CHANGED, args));
1980 }
1981 };
1982
1983 final ActivityManager activityManager =
1984 mContext.getSystemService(ActivityManager.class);
1985 activityManager.registerUidFrozenStateChangedCallback(
1986 (Runnable r) -> r.run(), frozenStateChangedCallback);
1987 }
Yuyang Huang41557552023-11-28 12:47:22 +09001988
1989 if (mDeps.isFeatureNotChickenedOut(mContext, LOG_BPF_RC)) {
1990 mHandler.post(BpfLoaderRcUtils::checkBpfLoaderRc);
1991 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001992 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001993
Xiao Ma0a171c02022-01-23 16:14:51 +00001994 /**
1995 * Check whether or not the device supports Ethernet transport.
1996 */
1997 public static boolean deviceSupportsEthernet(final Context context) {
1998 final PackageManager pm = context.getPackageManager();
1999 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
2000 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
2001 }
2002
Chalard Jean46adcf32018-04-18 20:18:38 +09002003 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002004 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
2005 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09002006 }
2007
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002008 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
2009 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09002010 final NetworkCapabilities netCap = new NetworkCapabilities();
2011 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002012 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09002013 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08002014 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09002015 return netCap;
2016 }
2017
James Mattis45d81842021-01-10 14:24:24 -08002018 private NetworkRequest createDefaultRequest() {
2019 return createDefaultInternetRequestForTransport(
2020 TYPE_NONE, NetworkRequest.Type.REQUEST);
2021 }
2022
lucaslin3ba7cc22022-12-19 02:35:33 +00002023 private NetworkRequest createVpnRequest() {
2024 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
2025 .withoutDefaultCapabilities()
2026 .addTransportType(TRANSPORT_VPN)
2027 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
2028 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
2029 .build();
2030 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2031 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
2032 }
2033
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09002034 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002035 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09002036 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09002037 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08002038 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08002039 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08002040 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09002041 netCap.addTransportType(transportType);
2042 }
James Mattis45d81842021-01-10 14:24:24 -08002043 return createNetworkRequest(type, netCap);
2044 }
2045
2046 private NetworkRequest createNetworkRequest(
2047 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09002048 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09002049 }
2050
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002051 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
2052 NetworkRequest.Type type) {
2053 final NetworkCapabilities netCap = new NetworkCapabilities();
2054 netCap.clearAll();
2055 netCap.addCapability(capability);
2056 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
2057 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
2058 }
2059
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002060 // Used only for testing.
2061 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07002062 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002063 // changing ContentResolver to make registerContentObserver non-final).
2064 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
2065 // by subclassing SettingsObserver.
2066 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002067 void updateAlwaysOnNetworks() {
2068 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09002069 }
2070
Erik Kline9a62f012018-03-21 07:18:33 -07002071 // See FakeSettingsProvider comment above.
2072 @VisibleForTesting
2073 void updatePrivateDnsSettings() {
2074 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
2075 }
2076
paulhu51f77dc2021-06-07 02:34:20 +00002077 @VisibleForTesting
2078 void updateMobileDataPreferredUids() {
2079 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
2080 }
2081
Patrick Rohr2857ac42022-01-21 14:58:16 +01002082 @VisibleForTesting
2083 void updateIngressRateLimit() {
2084 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
2085 }
2086
Aaron Huang40b52442021-06-08 04:34:24 +08002087 @VisibleForTesting
2088 void simulateUpdateProxyInfo(@Nullable final Network network,
2089 @NonNull final ProxyInfo proxyInfo) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08002090 Message.obtain(mHandler, EVENT_PAC_PROXY_HAS_CHANGED,
Aaron Huang40b52442021-06-08 04:34:24 +08002091 new Pair<>(network, proxyInfo)).sendToTarget();
2092 }
2093
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00002094 /**
2095 * Called when satellite network fallback uids at {@link SatelliteAccessController}
2096 * cache was updated based on {@link
2097 * android.app.role.OnRoleHoldersChangedListener#onRoleHoldersChanged(String, UserHandle)},
2098 * to create multilayer request with preference order
2099 * {@link #PREFERENCE_ORDER_SATELLITE_FALLBACK} there on.
2100 *
2101 */
2102 private void updateSatelliteNetworkPreferenceUids(Set<Integer> satelliteNetworkFallbackUids) {
2103 handleSetSatelliteNetworkPreference(satelliteNetworkFallbackUids);
2104 }
2105
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002106 private void handleAlwaysOnNetworkRequest(
2107 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09002108 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002109 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08002110 handleAlwaysOnNetworkRequest(networkRequest, enable);
2111 }
2112
2113 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002114 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09002115 if (enable == isEnabled) {
2116 return; // Nothing to do.
2117 }
2118
2119 if (enable) {
2120 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09002121 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08002122 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08002123 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09002124 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08002125 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
2126 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09002127 }
2128 }
2129
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002130 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08002131 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
2132 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
2133 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
2134 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09002135 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
2136 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09002137 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002138 }
2139
paulhu51f77dc2021-06-07 02:34:20 +00002140 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08002141 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09002142 private void registerSettingsCallbacks() {
2143 // Watch for global HTTP proxy changes.
2144 mSettingsObserver.observe(
2145 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
2146 EVENT_APPLY_GLOBAL_HTTP_PROXY);
2147
Chalard Jean46bfbf02022-02-02 00:56:25 +09002148 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09002149 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002150 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002151 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
2152
Chalard Jean46bfbf02022-02-02 00:56:25 +09002153 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002154 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08002155 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07002156 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00002157
2158 // Watch for mobile data preferred uids changes.
2159 mSettingsObserver.observe(
2160 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
2161 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01002162
2163 // Watch for ingress rate limit changes.
2164 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01002165 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01002166 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
2167 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09002168 }
2169
Erik Kline31b4a9e2018-01-11 21:07:29 +09002170 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07002171 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
2172 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09002173 }
2174 }
2175
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002176 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08002177 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
2178 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07002179 return mNextNetworkRequestId++;
2180 }
2181
junyulai74f9a8b2018-06-13 15:00:37 +08002182 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09002183 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08002184 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002185 if (network == null) {
2186 return null;
2187 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08002188 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07002189 }
2190
2191 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002192 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07002193 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002194 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002195 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002196
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002197 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002198 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002199 private NetworkAgentInfo getVpnForUid(int uid) {
2200 synchronized (mNetworkForNetId) {
2201 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2202 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09002203 if (nai.isVPN() && nai.everConnected()
2204 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002205 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002206 }
2207 }
2208 }
2209 return null;
2210 }
2211
Chalard Jean46bfbf02022-02-02 00:56:25 +09002212 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002213 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09002214 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002215 final NetworkAgentInfo nai = getVpnForUid(uid);
2216 if (nai != null) return nai.declaredUnderlyingNetworks;
2217 return null;
2218 }
2219
Lorenzo Colittia7574052021-01-19 01:33:05 +09002220 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08002221 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002222
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002223 final Network[] networks = getVpnUnderlyingNetworks(uid);
2224 if (networks != null) {
2225 // getUnderlyingNetworks() returns:
2226 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
2227 // empty array => the VPN explicitly said "no default network".
2228 // non-empty array => the VPN specified one or more default networks; we use the
2229 // first one.
2230 if (networks.length > 0) {
2231 nai = getNetworkAgentInfoForNetwork(networks[0]);
2232 } else {
2233 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08002234 }
2235 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002236 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04002237 }
2238
2239 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002240 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04002241 */
paulhu7aeba372020-12-30 00:42:19 +08002242 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
2243 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002244 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09002245 if (ignoreBlocked) {
2246 return false;
2247 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09002248 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08002249 final long ident = Binder.clearCallingIdentity();
2250 try {
2251 final boolean metered = nc == null ? true : nc.isMetered();
2252 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
2253 } finally {
2254 Binder.restoreCallingIdentity(ident);
2255 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002256 }
2257
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002258 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09002259 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
2260 return;
2261 }
Hugo Benichi47011212017-03-30 10:46:05 +09002262 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002263 synchronized (mBlockedAppUids) {
2264 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002265 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002266 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09002267 blocked = false;
2268 } else {
2269 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002270 }
2271 }
Hugo Benichi47011212017-03-30 10:46:05 +09002272 String action = blocked ? "BLOCKED" : "UNBLOCKED";
2273 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
2274 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09002275 }
2276
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002277 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08002278 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
2279 return;
2280 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002281 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08002282 final int requestId = nri.getActiveRequest() != null
2283 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08002284 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09002285 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00002286 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08002287 }
2288
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002289 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09002290 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002291 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08002292 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002293 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09002294 @NonNull
2295 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
2296 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09002297 final NetworkInfo filtered = new NetworkInfo(networkInfo);
2298 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
2299 // but only exists if an app asks about them or requests them. Ensure the requesting app
2300 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09002301 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002302 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
2303 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
2304 null /* extraInfo */);
2305 }
2306 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002307 return filtered;
2308 }
2309
2310 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
2311 boolean ignoreBlocked) {
2312 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
2313 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002314 }
2315
2316 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002317 * Return NetworkInfo for the active (i.e., connected) network interface.
2318 * It is assumed that at most one network is active at a time. If more
2319 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002320 * @return the info for the active network, or {@code null} if none is
2321 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002322 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002323 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002324 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002325 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002326 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002327 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002328 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2329 if (nai == null) return null;
2330 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2331 maybeLogBlockedNetworkInfo(networkInfo, uid);
2332 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002333 }
2334
Paul Jensen1f567382015-02-13 14:18:39 -05002335 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002336 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002337 public Network getActiveNetwork() {
2338 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002339 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002340 }
2341
2342 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002343 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002344 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002345 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002346 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002347 }
2348
Chalard Jean46bfbf02022-02-02 00:56:25 +09002349 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002350 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002351 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2352 if (vpnNai != null) {
2353 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2354 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2355 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002356 }
Paul Jensen1f567382015-02-13 14:18:39 -05002357 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002358
James Mattis2516da32021-01-31 17:06:19 -08002359 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002360 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2361 ignoreBlocked)) {
2362 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002363 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002364 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002365 }
2366
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002367 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002368 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002369 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002370 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002371 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2372 if (nai == null) return null;
2373 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002374 }
2375
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002376 /** Returns a NetworkInfo object for a network that doesn't exist. */
2377 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2378 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2379 getNetworkTypeName(networkType), "" /* subtypeName */);
2380 info.setIsAvailable(true);
2381 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2382 // background data is restricted.
2383 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2384 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2385 ? DetailedState.BLOCKED
2386 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002387 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2388 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002389 return info;
2390 }
2391
Lorenzo Colittia7574052021-01-19 01:33:05 +09002392 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002393 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2394 return null;
2395 }
2396 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002397 if (nai == null) {
2398 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002399 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002400 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2401 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002402 }
2403
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002404 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002405 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002406 public NetworkInfo getNetworkInfo(int networkType) {
2407 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002408 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002409 if (getVpnUnderlyingNetworks(uid) != null) {
2410 // A VPN is active, so we may need to return one of its underlying networks. This
2411 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002412 // getNetworkAgentInfoForUid.
2413 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2414 if (nai == null) return null;
2415 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2416 if (networkInfo.getType() == networkType) {
2417 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002418 }
2419 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002420 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002421 }
2422
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002423 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002424 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002425 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002426 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002427 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002428 if (nai == null) return null;
2429 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002430 }
2431
2432 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002433 public NetworkInfo[] getAllNetworkInfo() {
2434 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002435 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002436 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2437 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002438 NetworkInfo info = getNetworkInfo(networkType);
2439 if (info != null) {
2440 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002441 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002442 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002443 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002444 }
2445
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002446 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002447 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002448 public Network getNetworkForType(int networkType) {
2449 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002450 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2451 return null;
2452 }
2453 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2454 if (nai == null) {
2455 return null;
2456 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002457 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002458 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2459 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002460 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002461 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002462 }
2463
2464 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002465 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002466 public Network[] getAllNetworks() {
2467 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002468 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002469 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002470 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002471 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002472 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002473 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002474 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002475 }
2476
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002477 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002478 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002479 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002480 // The basic principle is: if an app's traffic could possibly go over a
2481 // network, without the app doing anything multinetwork-specific,
2482 // (hence, by "default"), then include that network's capabilities in
2483 // the array.
2484 //
2485 // In the normal case, app traffic only goes over the system's default
2486 // network connection, so that's the only network returned.
2487 //
2488 // With a VPN in force, some app traffic may go into the VPN, and thus
2489 // over whatever underlying networks the VPN specifies, while other app
2490 // traffic may go over the system default network (e.g.: a split-tunnel
2491 // VPN, or an app disallowed by the VPN), so the set of networks
2492 // returned includes the VPN's underlying networks and the system
2493 // default.
2494 enforceAccessPermission();
2495
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002496 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002497
James Mattis2516da32021-01-31 17:06:19 -08002498 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2499 if (!nri.isBeingSatisfied()) {
2500 continue;
2501 }
2502 final NetworkAgentInfo nai = nri.getSatisfier();
2503 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2504 if (null != nc
2505 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2506 && !result.containsKey(nai.network)) {
2507 result.put(
2508 nai.network,
2509 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002510 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002511 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2512 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002513 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002514 }
2515
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002516 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002517 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002518 if (null != networks) {
2519 for (final Network network : networks) {
2520 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2521 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002522 result.put(
2523 network,
2524 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002525 nc,
2526 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002527 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002528 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002529 }
2530 }
2531 }
2532
2533 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2534 out = result.values().toArray(out);
2535 return out;
2536 }
2537
Chalard Jeanf95e2de2023-08-22 19:07:47 +09002538 // Because StatsEvent is not usable in tests (everything inside it is hidden), this
2539 // method is used to convert a ConnectivityStateSample into a StatsEvent, so that tests
2540 // can call sampleConnectivityState and make the checks on it.
2541 @NonNull
2542 private StatsEvent sampleConnectivityStateToStatsEvent() {
2543 final ConnectivityStateSample sample = sampleConnectivityState();
2544 return ConnectivityStatsLog.buildStatsEvent(
2545 ConnectivityStatsLog.CONNECTIVITY_STATE_SAMPLE,
2546 sample.getNetworkCountPerTransports().toByteArray(),
2547 sample.getConnectionDurationPerTransports().toByteArray(),
2548 sample.getNetworkRequestCount().toByteArray(),
2549 sample.getNetworks().toByteArray());
2550 }
2551
2552 /**
2553 * Gather and return a snapshot of the current connectivity state, to be used as a sample.
2554 *
2555 * This is used for metrics. These snapshots will be sampled and constitute a base for
2556 * statistics about connectivity state of devices.
2557 */
2558 @VisibleForTesting
2559 @NonNull
2560 public ConnectivityStateSample sampleConnectivityState() {
2561 ensureRunningOnConnectivityServiceThread();
2562 final ConnectivityStateSample.Builder builder = ConnectivityStateSample.newBuilder();
2563 builder.setNetworkCountPerTransports(sampleNetworkCount(mNetworkAgentInfos));
2564 builder.setConnectionDurationPerTransports(sampleConnectionDuration(mNetworkAgentInfos));
2565 builder.setNetworkRequestCount(sampleNetworkRequestCount(mNetworkRequests.values()));
2566 builder.setNetworks(sampleNetworks(mNetworkAgentInfos));
2567 return builder.build();
2568 }
2569
2570 private static NetworkCountPerTransports sampleNetworkCount(
2571 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2572 final SparseIntArray countPerTransports = new SparseIntArray();
2573 for (final NetworkAgentInfo nai : nais) {
2574 int transports = (int) nai.networkCapabilities.getTransportTypesInternal();
2575 countPerTransports.put(transports, 1 + countPerTransports.get(transports, 0));
2576 }
2577 final NetworkCountPerTransports.Builder builder = NetworkCountPerTransports.newBuilder();
2578 for (int i = countPerTransports.size() - 1; i >= 0; --i) {
2579 final NetworkCountForTransports.Builder c = NetworkCountForTransports.newBuilder();
2580 c.setTransportTypes(countPerTransports.keyAt(i));
2581 c.setNetworkCount(countPerTransports.valueAt(i));
2582 builder.addNetworkCountForTransports(c);
2583 }
2584 return builder.build();
2585 }
2586
2587 private static ConnectionDurationPerTransports sampleConnectionDuration(
2588 @NonNull final ArraySet<NetworkAgentInfo> nais) {
2589 final ConnectionDurationPerTransports.Builder builder =
2590 ConnectionDurationPerTransports.newBuilder();
2591 for (final NetworkAgentInfo nai : nais) {
2592 final ConnectionDurationForTransports.Builder c =
2593 ConnectionDurationForTransports.newBuilder();
2594 c.setTransportTypes((int) nai.networkCapabilities.getTransportTypesInternal());
2595 final long durationMillis = SystemClock.elapsedRealtime() - nai.getConnectedTime();
2596 final long millisPerSecond = TimeUnit.SECONDS.toMillis(1);
2597 // Add millisPerSecond/2 to round up or down to the nearest value
2598 c.setDurationSec((int) ((durationMillis + millisPerSecond / 2) / millisPerSecond));
2599 builder.addConnectionDurationForTransports(c);
2600 }
2601 return builder.build();
2602 }
2603
2604 private static NetworkRequestCount sampleNetworkRequestCount(
2605 @NonNull final Collection<NetworkRequestInfo> nris) {
2606 final NetworkRequestCount.Builder builder = NetworkRequestCount.newBuilder();
2607 final SparseIntArray countPerType = new SparseIntArray();
2608 for (final NetworkRequestInfo nri : nris) {
2609 final int type;
2610 if (Process.SYSTEM_UID == nri.mAsUid) {
2611 // The request is filed "as" the system, so it's the system on its own behalf.
2612 type = RequestType.RT_SYSTEM.getNumber();
2613 } else if (Process.SYSTEM_UID == nri.mUid) {
2614 // The request is filed by the system as some other app, so it's the system on
2615 // behalf of an app.
2616 type = RequestType.RT_SYSTEM_ON_BEHALF_OF_APP.getNumber();
2617 } else {
2618 // Not the system, so it's an app requesting on its own behalf.
2619 type = RequestType.RT_APP.getNumber();
2620 }
2621 countPerType.put(type, countPerType.get(type, 0));
2622 }
2623 for (int i = countPerType.size() - 1; i >= 0; --i) {
2624 final RequestCountForType.Builder r = RequestCountForType.newBuilder();
2625 r.setRequestType(RequestType.forNumber(countPerType.keyAt(i)));
2626 r.setRequestCount(countPerType.valueAt(i));
2627 builder.addRequestCountForType(r);
2628 }
2629 return builder.build();
2630 }
2631
2632 private static NetworkList sampleNetworks(@NonNull final ArraySet<NetworkAgentInfo> nais) {
2633 final NetworkList.Builder builder = NetworkList.newBuilder();
2634 for (final NetworkAgentInfo nai : nais) {
2635 final NetworkCapabilities nc = nai.networkCapabilities;
2636 final NetworkDescription.Builder d = NetworkDescription.newBuilder();
2637 d.setTransportTypes((int) nc.getTransportTypesInternal());
2638 final MeteredState meteredState;
2639 if (nc.hasCapability(NET_CAPABILITY_TEMPORARILY_NOT_METERED)) {
2640 meteredState = MeteredState.METERED_TEMPORARILY_UNMETERED;
2641 } else if (nc.hasCapability(NET_CAPABILITY_NOT_METERED)) {
2642 meteredState = MeteredState.METERED_NO;
2643 } else {
2644 meteredState = MeteredState.METERED_YES;
2645 }
2646 d.setMeteredState(meteredState);
2647 final ValidatedState validatedState;
2648 if (nc.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) {
2649 validatedState = ValidatedState.VS_PORTAL;
2650 } else if (nc.hasCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
2651 validatedState = ValidatedState.VS_PARTIAL;
2652 } else if (nc.hasCapability(NET_CAPABILITY_VALIDATED)) {
2653 validatedState = ValidatedState.VS_VALID;
2654 } else {
2655 validatedState = ValidatedState.VS_INVALID;
2656 }
2657 d.setValidatedState(validatedState);
2658 d.setScorePolicies(nai.getScore().getPoliciesInternal());
2659 d.setCapabilities(nc.getCapabilitiesInternal());
2660 d.setEnterpriseId(nc.getEnterpriseIdsInternal());
2661 builder.addNetworkDescription(d);
2662 }
2663 return builder.build();
2664 }
2665
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002666 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002667 public boolean isNetworkSupported(int networkType) {
2668 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002669 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002670 }
2671
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002672 /**
2673 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002674 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002675 * @return the ip properties for the active network, or {@code null} if
2676 * none is active
2677 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002678 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002679 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002680 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002681 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002682 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2683 if (nai == null) return null;
2684 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002685 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002686 }
2687
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002688 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002689 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002690 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002691 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002692 final LinkProperties lp = getLinkProperties(nai);
2693 if (lp == null) return null;
2694 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002695 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002696 }
2697
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002698 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002699 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002700 public LinkProperties getLinkProperties(Network network) {
2701 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002702 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2703 if (lp == null) return null;
2704 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002705 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002706 }
2707
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002708 @Nullable
2709 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002710 if (nai == null) {
2711 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002712 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002713 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002714 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002715 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002716 }
2717
lucaslinc582d502022-01-27 09:07:00 +08002718 @Override
2719 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002720 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002721 @NonNull String packageName, @Nullable String callingAttributionTag) {
2722 Objects.requireNonNull(packageName);
2723 Objects.requireNonNull(lp);
2724 enforceNetworkStackOrSettingsPermission();
Junyu Lai71b51532024-02-01 10:39:01 +08002725 if (!hasAccessPermission(-1 /* pid */, uid)) {
lucaslinc582d502022-01-27 09:07:00 +08002726 return null;
2727 }
2728 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2729 }
2730
Qingxi Lib2748102020-01-08 12:51:49 -08002731 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2732 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2733 }
2734
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002735 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002736 if (nai == null) return null;
2737 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002738 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002739 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002740 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002741 }
2742
2743 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002744 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2745 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002746 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002747 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002748 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002749 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002750 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002751 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002752 }
2753
lucaslinc582d502022-01-27 09:07:00 +08002754 @Override
lucaslind2b06132022-03-02 10:56:57 +08002755 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2756 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2757 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002758 Objects.requireNonNull(nc);
2759 Objects.requireNonNull(packageName);
2760 enforceNetworkStackOrSettingsPermission();
Junyu Lai71b51532024-02-01 10:39:01 +08002761 if (!hasAccessPermission(-1 /* pid */, uid)) {
lucaslinc582d502022-01-27 09:07:00 +08002762 return null;
2763 }
2764 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2765 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2766 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2767 callingAttributionTag);
2768 }
2769
lucaslin69e1aa92022-03-22 18:15:09 +08002770 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2771 if (nc.getUnderlyingNetworks() != null
Junyu Lai71b51532024-02-01 10:39:01 +08002772 && !hasNetworkFactoryOrSettingsPermission(pid, uid)) {
lucaslin69e1aa92022-03-22 18:15:09 +08002773 nc.setUnderlyingNetworks(null);
2774 }
2775 }
2776
Chalard Jean53017782022-11-24 17:13:44 +09002777 private boolean canSeeAllowedUids(final int pid, final int uid, final int netOwnerUid) {
2778 return Process.SYSTEM_UID == uid
Junyu Lai71b51532024-02-01 10:39:01 +08002779 || hasAnyPermissionOf(mContext, pid, uid,
Chalard Jean53017782022-11-24 17:13:44 +09002780 android.Manifest.permission.NETWORK_FACTORY);
2781 }
2782
Qingxi Libb8da982020-01-17 17:54:27 -08002783 @VisibleForTesting
2784 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002785 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002786 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2787 // this would be expensive (one more permission check every time any NC callback is
2788 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2789 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2790 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002791 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Junyu Lai71b51532024-02-01 10:39:01 +08002792 if (!hasSettingsPermission(callerPid, callerUid)) {
Chalard Jean46adcf32018-04-18 20:18:38 +09002793 newNc.setUids(null);
2794 newNc.setSSID(null);
2795 }
Etan Cohen107ae952018-12-30 17:59:59 -08002796 if (newNc.getNetworkSpecifier() != null) {
2797 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2798 }
Junyu Lai71b51532024-02-01 10:39:01 +08002799 if (!hasAnyPermissionOf(mContext, callerPid, callerUid,
Junyu Lai4c6fe232023-04-11 11:33:46 +08002800 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002801 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2802 newNc.setAdministratorUids(new int[0]);
2803 }
Chalard Jean53017782022-11-24 17:13:44 +09002804 if (!canSeeAllowedUids(callerPid, callerUid, newNc.getOwnerUid())) {
Chalard Jeande665262022-02-25 16:12:12 +09002805 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002806 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002807 }
lucaslin69e1aa92022-03-22 18:15:09 +08002808 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002809
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002810 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002811 }
2812
Roshan Pius98f59ec2021-02-23 08:47:39 -08002813 /**
2814 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002815 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002816 * NetworkCapabilities.
2817 * Note: This wrapper does not support any sort of invalidation and thus must not be
2818 * persistent or long-lived. It may only be used for the time necessary to
2819 * compute the redactions required by one particular NetworkCallback or
2820 * synchronous call.
2821 */
2822 private class RedactionPermissionChecker {
2823 private final int mCallingPid;
2824 private final int mCallingUid;
2825 @NonNull private final String mCallingPackageName;
2826 @Nullable private final String mCallingAttributionTag;
2827
2828 private Boolean mHasLocationPermission = null;
2829 private Boolean mHasLocalMacAddressPermission = null;
2830 private Boolean mHasSettingsPermission = null;
2831
2832 RedactionPermissionChecker(int callingPid, int callingUid,
2833 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2834 mCallingPid = callingPid;
2835 mCallingUid = callingUid;
2836 mCallingPackageName = callingPackageName;
2837 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002838 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002839
2840 private boolean hasLocationPermissionInternal() {
2841 final long token = Binder.clearCallingIdentity();
2842 try {
2843 return mLocationPermissionChecker.checkLocationPermission(
2844 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2845 null /* message */);
2846 } finally {
2847 Binder.restoreCallingIdentity(token);
2848 }
2849 }
2850
2851 /**
2852 * Returns whether the app holds location permission or not (might return cached result
2853 * if the permission was already checked before).
2854 */
2855 public boolean hasLocationPermission() {
2856 if (mHasLocationPermission == null) {
2857 // If there is no cached result, perform the check now.
2858 mHasLocationPermission = hasLocationPermissionInternal();
2859 }
2860 return mHasLocationPermission;
2861 }
2862
2863 /**
2864 * Returns whether the app holds local mac address permission or not (might return cached
2865 * result if the permission was already checked before).
2866 */
Junyu Lai71b51532024-02-01 10:39:01 +08002867 @CheckResult
Roshan Pius98f59ec2021-02-23 08:47:39 -08002868 public boolean hasLocalMacAddressPermission() {
2869 if (mHasLocalMacAddressPermission == null) {
2870 // If there is no cached result, perform the check now.
Junyu Lai71b51532024-02-01 10:39:01 +08002871 mHasLocalMacAddressPermission = ConnectivityService.this
2872 .hasLocalMacAddressPermission(mCallingPid, mCallingUid);
Roshan Pius98f59ec2021-02-23 08:47:39 -08002873 }
2874 return mHasLocalMacAddressPermission;
2875 }
2876
2877 /**
2878 * Returns whether the app holds settings permission or not (might return cached
2879 * result if the permission was already checked before).
2880 */
Junyu Lai71b51532024-02-01 10:39:01 +08002881 @CheckResult
Roshan Pius98f59ec2021-02-23 08:47:39 -08002882 public boolean hasSettingsPermission() {
2883 if (mHasSettingsPermission == null) {
2884 // If there is no cached result, perform the check now.
Junyu Lai71b51532024-02-01 10:39:01 +08002885 mHasSettingsPermission =
2886 ConnectivityService.this.hasSettingsPermission(mCallingPid, mCallingUid);
Roshan Pius98f59ec2021-02-23 08:47:39 -08002887 }
2888 return mHasSettingsPermission;
2889 }
2890 }
2891
2892 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2893 @NetworkCapabilities.NetCapability long redaction) {
2894 return (redactions & redaction) != 0;
2895 }
2896
2897 /**
2898 * Use the provided |applicableRedactions| to check the receiving app's
2899 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2900 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2901 * before being sent to the corresponding app.
2902 */
2903 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2904 @NetworkCapabilities.RedactionType long applicableRedactions,
2905 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2906 boolean includeLocationSensitiveInfo) {
2907 long redactions = applicableRedactions;
2908 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2909 if (includeLocationSensitiveInfo
2910 && redactionPermissionChecker.hasLocationPermission()) {
2911 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2912 }
2913 }
2914 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2915 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2916 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2917 }
2918 }
2919 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2920 if (redactionPermissionChecker.hasSettingsPermission()) {
2921 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2922 }
2923 }
2924 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002925 }
2926
Qingxi Lib2748102020-01-08 12:51:49 -08002927 @VisibleForTesting
2928 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002929 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002930 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002931 int callingPid, int callingUid, @NonNull String callingPkgName,
2932 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002933 if (nc == null) {
2934 return null;
2935 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002936 // Avoid doing location permission check if the transport info has no location sensitive
2937 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002938 final RedactionPermissionChecker redactionPermissionChecker =
2939 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2940 callingAttributionTag);
2941 final long redactions = retrieveRequiredRedactions(
2942 nc.getApplicableRedactions(), redactionPermissionChecker,
2943 includeLocationSensitiveInfo);
2944 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002945 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002946 // TODO : calling UID is redacted because apps should generally not know what UID is
2947 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002948 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002949 newNc.setOwnerUid(INVALID_UID);
2950 return newNc;
2951 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002952 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2953 if (nc.hasTransport(TRANSPORT_VPN)) {
2954 // Owner UIDs already checked above. No need to re-check.
2955 return newNc;
2956 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002957 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2958 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002959 // compatibility for older apps.
2960 if (!includeLocationSensitiveInfo
2961 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002962 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002963 newNc.setOwnerUid(INVALID_UID);
2964 return newNc;
2965 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002966 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002967 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002968 newNc.setOwnerUid(INVALID_UID);
2969 }
Qingxi Lib2748102020-01-08 12:51:49 -08002970 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002971 }
2972
lucaslinc582d502022-01-27 09:07:00 +08002973 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002974 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2975 LinkProperties lp, int callerPid, int callerUid) {
2976 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002977 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2978 // this would be expensive (one more permission check every time any LP callback is
2979 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2980 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2981 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002982
2983 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2984 final boolean needsSanitization =
2985 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2986 if (!needsSanitization) {
2987 return new LinkProperties(lp);
2988 }
2989
Junyu Lai71b51532024-02-01 10:39:01 +08002990 if (hasSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002991 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002992 }
2993
2994 final LinkProperties newLp = new LinkProperties(lp);
2995 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2996 // object gets parceled.
2997 newLp.setCaptivePortalApiUrl(null);
2998 newLp.setCaptivePortalData(null);
2999 return newLp;
3000 }
3001
Roshan Pius08c94fb2020-01-16 12:17:17 -08003002 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
3003 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003004 // There is no need to track the effective UID of the request here. If the caller
3005 // lacks the settings permission, the effective UID is the same as the calling ID.
Junyu Lai71b51532024-02-01 10:39:01 +08003006 if (!hasSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09003007 // Unprivileged apps can only pass in null or their own UID.
3008 if (nc.getUids() == null) {
3009 // If the caller passes in null, the callback will also match networks that do not
3010 // apply to its UID, similarly to what it would see if it called getAllNetworks.
3011 // In this case, redact everything in the request immediately. This ensures that the
3012 // app is not able to get any redacted information by filing an unredacted request
3013 // and observing whether the request matches something.
3014 if (nc.getNetworkSpecifier() != null) {
3015 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
3016 }
3017 } else {
3018 nc.setSingleUid(callerUid);
3019 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09003020 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08003021 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07003022 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08003023
3024 // Clear owner UID; this can never come from an app.
3025 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003026 }
3027
Chalard Jean38354d12018-03-20 19:13:57 +09003028 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003029 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09003030 nc.addCapability(NET_CAPABILITY_FOREGROUND);
3031 }
3032 }
3033
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09003034 @Override
3035 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
3036 enforceAccessPermission();
3037 final int callerUid = Binder.getCallingUid();
3038 final long token = Binder.clearCallingIdentity();
3039 try {
3040 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
3041 } finally {
3042 Binder.restoreCallingIdentity(token);
3043 }
3044 }
3045
junyulaiebd15162021-03-03 12:09:05 +08003046 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09003047 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07003048 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08003049 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08003050 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08003051
Serik Beketayev05130302021-01-15 16:47:25 -08003052 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08003053 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08003054 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
3055 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08003056 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08003057 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08003058 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08003059 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
3060 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07003061 }
3062 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09003063 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07003064 }
3065
Jeff Sharkey66fa9682011-08-02 17:22:34 -07003066 @Override
junyulaiebd15162021-03-03 12:09:05 +08003067 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08003068 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08003069 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08003070 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08003071
3072 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
3073 for (Network network : getAllNetworks()) {
3074 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09003075 final boolean includeNetwork = (nai != null) && nai.isCreated();
3076 if (includeNetwork) {
junyulaiebd15162021-03-03 12:09:05 +08003077 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
3078 // NetworkCapabilities, which may contain UIDs of apps to which the
3079 // network applies. Should the UIDs be cleared so as not to leak or
3080 // interfere ?
3081 result.add(nai.getNetworkStateSnapshot());
3082 }
3083 }
3084 return result;
3085 }
3086
3087 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003088 public boolean isActiveNetworkMetered() {
3089 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07003090
Qingxi Lib2748102020-01-08 12:51:49 -08003091 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06003092 if (caps != null) {
3093 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3094 } else {
3095 // Always return the most conservative value
3096 return true;
3097 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07003098 }
3099
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07003100 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09003101 * Ensures that the system cannot call a particular method.
3102 */
3103 private boolean disallowedBecauseSystemCaller() {
3104 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07003105 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
3106 // for devices launched with Q and above. However, existing devices upgrading to Q and
3107 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003108 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07003109 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003110 log("This method exists only for app backwards compatibility"
3111 + " and must not be called by system services.");
3112 return true;
3113 }
3114 return false;
3115 }
3116
3117 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08003118 * Ensure that a network route exists to deliver traffic to the specified
3119 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07003120 * @param networkType the type of the network over which traffic to the
3121 * specified host is to be routed
3122 * @param hostAddress the IP address of the host to which the route is
3123 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08003124 * @return {@code true} on success, {@code false} on failure
3125 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09003126 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003127 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
3128 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09003129 if (disallowedBecauseSystemCaller()) {
3130 return false;
3131 }
Junyu Lai8fdc4312024-01-16 11:19:43 +08003132 PermissionUtils.enforcePackageNameMatchesUid(
3133 mContext, mDeps.getCallingUid(), callingPackageName);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003134 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003135 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003136 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003137 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003138
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003139 InetAddress addr;
3140 try {
3141 addr = InetAddress.getByAddress(hostAddress);
3142 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003143 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08003144 return false;
3145 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07003146
The Android Open Source Project28527d22009-03-03 19:31:44 -08003147 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003148 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08003149 return false;
3150 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003151
3152 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
3153 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003154 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003155 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
3156 } else {
3157 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
3158 }
3159 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08003160 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003161
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003162 DetailedState netState;
3163 synchronized (nai) {
3164 netState = nai.networkInfo.getDetailedState();
3165 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003166
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003167 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07003168 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07003169 log("requestRouteToHostAddress on down network "
3170 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07003171 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07003172 }
3173 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003174 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003175
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003176 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003177 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07003178 try {
Paul Jensen65743a22014-07-11 08:17:29 -04003179 LinkProperties lp;
3180 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003181 synchronized (nai) {
3182 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08003183 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07003184 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003185 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09003186 if (DBG) {
3187 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
3188 }
Wink Saville32506bc2013-06-29 21:10:57 -07003189 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003190 } finally {
3191 Binder.restoreCallingIdentity(token);
3192 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003193 }
3194
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003195 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003196 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07003197 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003198 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07003199 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09003200 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07003201 if (bestRoute.getGateway().equals(addr)) {
3202 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003203 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003204 } else {
3205 // if we will connect to this through another route, add a direct route
3206 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08003207 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07003208 }
3209 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09003210 if (DBG) log("Adding legacy route " + bestRoute +
3211 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08003212
3213 final String dst = bestRoute.getDestinationLinkAddress().toString();
3214 final String nextHop = bestRoute.hasGateway()
3215 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003216 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08003217 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
3218 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07003219 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08003220 return false;
3221 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07003222 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003223 }
3224
paulhu7c0a2e62021-01-08 00:51:49 +08003225 class DnsResolverUnsolicitedEventCallback extends
3226 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05003227 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003228 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05003229 try {
3230 mHandler.sendMessage(mHandler.obtainMessage(
3231 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08003232 new PrivateDnsValidationUpdate(event.netId,
3233 InetAddresses.parseNumericAddress(event.ipAddress),
3234 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05003235 } catch (IllegalArgumentException e) {
3236 loge("Error parsing ip address in validation event");
3237 }
3238 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08003239
3240 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003241 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
3242 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003243 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
3244 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
3245 // event callback for certain nai. e.g. cellular. Register here to pass to
3246 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003247 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09003248 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
3249 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09003250 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08003251 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08003252 }
3253 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003254
3255 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003256 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
3257 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
3258 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09003259 }
dalyk1720e542018-03-05 12:42:22 -05003260
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003261 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08003262 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003263 return this.VERSION;
3264 }
3265
3266 @Override
3267 public String getInterfaceHash() {
3268 return this.HASH;
3269 }
paulhu7c0a2e62021-01-08 00:51:49 +08003270 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003271
3272 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08003273 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
3274 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09003275
paulhu7c0a2e62021-01-08 00:51:49 +08003276 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05003277 try {
paulhu7c0a2e62021-01-08 00:51:49 +08003278 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05003279 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08003280 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05003281 }
3282 }
3283
Sudheer Shanka9967d462021-03-18 19:09:25 +00003284 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003285 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003286 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003287 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
3288 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08003289 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07003290 };
3291
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003292 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003293 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09003294 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08003295 }
3296
Mark Fasheh7c999d82023-05-04 20:23:11 +00003297 static final class UidFrozenStateChangedArgs {
3298 final int[] mUids;
3299 final int[] mFrozenStates;
3300
3301 UidFrozenStateChangedArgs(int[] uids, int[] frozenStates) {
3302 mUids = uids;
3303 mFrozenStates = frozenStates;
3304 }
3305 }
3306
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003307 /**
3308 * Check if the cell network is idle.
3309 * @return true if the cell network state is idle
3310 * false if the cell network state is active or unknown
3311 */
3312 private boolean isCellNetworkIdle() {
3313 final NetworkAgentInfo defaultNai = getDefaultNetwork();
3314 if (defaultNai == null
3315 || !defaultNai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
3316 // mNetworkActivityTracker only tracks the activity of the default network. So if the
3317 // cell network is not the default network, cell network state is unknown.
3318 // TODO(b/279380356): Track cell network state when the cell is not the default network
3319 return false;
3320 }
3321
3322 return !mNetworkActivityTracker.isDefaultNetworkActive();
3323 }
3324
Mark Fasheh7c999d82023-05-04 20:23:11 +00003325 private void handleFrozenUids(int[] uids, int[] frozenStates) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003326 final ArraySet<Integer> ownerUids = new ArraySet<>();
Mark Fasheh7c999d82023-05-04 20:23:11 +00003327
3328 for (int i = 0; i < uids.length; i++) {
3329 if (frozenStates[i] == UID_FROZEN_STATE_FROZEN) {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003330 ownerUids.add(uids[i]);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003331 } else {
3332 mPendingFrozenUids.remove(uids[i]);
Mark Fasheh7c999d82023-05-04 20:23:11 +00003333 }
3334 }
3335
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003336 if (ownerUids.isEmpty()) {
3337 return;
3338 }
3339
3340 if (mDelayDestroyFrozenSockets && isCellNetworkIdle()) {
3341 // Delay closing sockets to avoid waking the cell modem up.
3342 // Wi-Fi network state is not considered since waking Wi-Fi modem up is much cheaper
3343 // than waking cell modem up.
3344 mPendingFrozenUids.addAll(ownerUids);
3345 } else {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003346 try {
Motomu Utsumi588a6452023-05-30 11:43:52 +09003347 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003348 } catch (SocketException | InterruptedIOException | ErrnoException e) {
Mark Fasheh7c999d82023-05-04 20:23:11 +00003349 loge("Exception in socket destroy: " + e);
3350 }
3351 }
3352 }
3353
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003354 private void closePendingFrozenSockets() {
3355 ensureRunningOnConnectivityServiceThread();
3356
3357 try {
3358 mDeps.destroyLiveTcpSocketsByOwnerUids(mPendingFrozenUids);
3359 } catch (SocketException | InterruptedIOException | ErrnoException e) {
3360 loge("Failed to close pending frozen app sockets: " + e);
3361 }
3362 mPendingFrozenUids.clear();
3363 }
3364
3365 private void handleReportNetworkActivity(final NetworkActivityParams params) {
3366 mNetworkActivityTracker.handleReportNetworkActivity(params);
3367
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003368 final boolean isCellNetworkActivity;
3369 if (mTrackMultiNetworkActivities) {
3370 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(params.label);
3371 // nai could be null if netd receives a netlink message and calls the network
3372 // activity change callback after the network is unregistered from ConnectivityService.
3373 isCellNetworkActivity = nai != null
3374 && nai.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3375 } else {
3376 isCellNetworkActivity = params.label == TRANSPORT_CELLULAR;
3377 }
3378
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003379 if (mDelayDestroyFrozenSockets
3380 && params.isActive
Motomu Utsumi5fce43e2023-05-29 15:21:43 +09003381 && isCellNetworkActivity
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003382 && !mPendingFrozenUids.isEmpty()) {
3383 closePendingFrozenSockets();
3384 }
3385 }
3386
3387 /**
3388 * If the cellular network is no longer the default network, close pending frozen sockets.
3389 *
3390 * @param newNetwork new default network
3391 * @param oldNetwork old default network
3392 */
3393 private void maybeClosePendingFrozenSockets(NetworkAgentInfo newNetwork,
3394 NetworkAgentInfo oldNetwork) {
3395 final boolean isOldNetworkCellular = oldNetwork != null
3396 && oldNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3397 final boolean isNewNetworkCellular = newNetwork != null
3398 && newNetwork.networkCapabilities.hasTransport(TRANSPORT_CELLULAR);
3399
3400 if (isOldNetworkCellular
3401 && !isNewNetworkCellular
3402 && !mPendingFrozenUids.isEmpty()) {
3403 closePendingFrozenSockets();
3404 }
3405 }
3406
3407 private void dumpCloseFrozenAppSockets(IndentingPrintWriter pw) {
3408 pw.println("CloseFrozenAppSockets:");
3409 pw.increaseIndent();
3410 pw.print("mDestroyFrozenSockets="); pw.println(mDestroyFrozenSockets);
3411 pw.print("mDelayDestroyFrozenSockets="); pw.println(mDelayDestroyFrozenSockets);
3412 pw.print("mPendingFrozenUids="); pw.println(mPendingFrozenUids);
3413 pw.decreaseIndent();
3414 }
3415
Junyu Lai155760b2023-10-05 14:51:00 +08003416 private void dumpBpfProgramStatus(IndentingPrintWriter pw) {
3417 pw.println("Bpf Program Status:");
3418 pw.increaseIndent();
3419 try {
3420 pw.print("CGROUP_INET_INGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003421 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003422 pw.print("CGROUP_INET_EGRESS: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003423 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
Junyu Lai155760b2023-10-05 14:51:00 +08003424 pw.print("CGROUP_INET_SOCK_CREATE: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003425 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
Junyu Lai155760b2023-10-05 14:51:00 +08003426 pw.print("CGROUP_INET4_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003427 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003428 pw.print("CGROUP_INET6_BIND: ");
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +00003429 pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
Junyu Lai155760b2023-10-05 14:51:00 +08003430 } catch (IOException e) {
3431 pw.println(" IOException");
3432 }
3433 pw.decreaseIndent();
3434 }
3435
Mark Fasheh7c999d82023-05-04 20:23:11 +00003436 @VisibleForTesting
3437 static final String KEY_DESTROY_FROZEN_SOCKETS_VERSION = "destroy_frozen_sockets_version";
Motomu Utsumi188bfd32023-05-30 14:38:04 +09003438 @VisibleForTesting
3439 static final String DELAY_DESTROY_FROZEN_SOCKETS_VERSION =
3440 "delay_destroy_frozen_sockets_version";
Mark Fasheh7c999d82023-05-04 20:23:11 +00003441
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003442 @VisibleForTesting
3443 public static final String ALLOW_SYSUI_CONNECTIVITY_REPORTS =
3444 "allow_sysui_connectivity_reports";
3445
Yuyang Huang41557552023-11-28 12:47:22 +09003446 public static final String LOG_BPF_RC = "log_bpf_rc_force_disable";
3447
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00003448 public static final String ALLOW_SATALLITE_NETWORK_FALLBACK =
3449 "allow_satallite_network_fallback";
3450
Paul Jensen83f5d572014-08-29 09:54:01 -04003451 private void enforceInternetPermission() {
3452 mContext.enforceCallingOrSelfPermission(
3453 android.Manifest.permission.INTERNET,
3454 "ConnectivityService");
3455 }
3456
The Android Open Source Project28527d22009-03-03 19:31:44 -08003457 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003458 mContext.enforceCallingOrSelfPermission(
3459 android.Manifest.permission.ACCESS_NETWORK_STATE,
3460 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003461 }
3462
Junyu Lai71b51532024-02-01 10:39:01 +08003463 @CheckResult
3464 private boolean hasAccessPermission(int pid, int uid) {
lucaslinc582d502022-01-27 09:07:00 +08003465 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
3466 == PERMISSION_GRANTED;
3467 }
3468
paulhua6ee2122021-02-22 15:40:43 +08003469 /**
3470 * Performs a strict and comprehensive check of whether a calling package is allowed to
3471 * change the state of network, as the condition differs for pre-M, M+, and
3472 * privileged/preinstalled apps. The caller is expected to have either the
3473 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
3474 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
3475 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
3476 * permission and cannot be revoked. See http://b/23597341
3477 *
3478 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
3479 * of this app will be updated to the current time.
3480 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07003481 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08003482 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
3483 == PackageManager.PERMISSION_GRANTED) {
3484 return;
3485 }
3486
3487 if (callingPkg == null) {
3488 throw new SecurityException("Calling package name is null.");
3489 }
3490
3491 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
3492 final int uid = mDeps.getCallingUid();
3493 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
3494 callingPkg, callingAttributionTag, null /* message */);
3495
3496 if (mode == AppOpsManager.MODE_ALLOWED) {
3497 return;
3498 }
3499
3500 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
3501 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
3502 return;
3503 }
3504
3505 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
3506 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
3507 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08003508 }
3509
Charles He9369e612017-05-15 17:07:18 +01003510 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003511 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01003512 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003513 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01003514 }
3515
Quang Luong98858d62023-02-11 00:25:24 +00003516 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003517 enforceAnyPermissionOf(mContext,
3518 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00003519 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08003520 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3521 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
3522 }
3523
paulhu8e96a752019-08-12 16:25:11 +08003524 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003525 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003526 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003527 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08003528 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08003529 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08003530 }
3531
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003532 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003533 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003534 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003535 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003536 android.Manifest.permission.NETWORK_SETTINGS,
3537 android.Manifest.permission.NETWORK_FACTORY,
3538 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3539 }
3540
3541 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003542 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003543 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08003544 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08003545 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3546 android.Manifest.permission.NETWORK_FACTORY,
3547 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3548 }
3549
Junyu Lai71b51532024-02-01 10:39:01 +08003550 @CheckResult
3551 private boolean hasNetworkFactoryOrSettingsPermission(int pid, int uid) {
lucaslin69e1aa92022-03-22 18:15:09 +08003552 return PERMISSION_GRANTED == mContext.checkPermission(
3553 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
3554 || PERMISSION_GRANTED == mContext.checkPermission(
3555 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3556 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09003557 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07003558 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08003559 }
3560
Junyu Lai71b51532024-02-01 10:39:01 +08003561 @CheckResult
3562 private boolean hasSettingsPermission() {
3563 return hasAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003564 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003565 }
3566
Junyu Lai71b51532024-02-01 10:39:01 +08003567 @CheckResult
3568 private boolean hasSettingsPermission(int pid, int uid) {
Chalard Jean9a396cc2018-02-21 18:43:54 +09003569 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003570 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
3571 || PERMISSION_GRANTED == mContext.checkPermission(
3572 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09003573 }
3574
paulhu8e96a752019-08-12 16:25:11 +08003575 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003576 enforceNetworkStackPermissionOr(mContext,
3577 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08003578 }
3579
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09003580 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08003581 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003582 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003583 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00003584 }
3585
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003586 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003587 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003588 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
3589 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08003590 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01003591 }
3592
James Mattis8378aec2021-01-26 14:05:36 -08003593 private void enforceOemNetworkPreferencesPermission() {
3594 mContext.enforceCallingOrSelfPermission(
3595 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3596 "ConnectivityService");
3597 }
3598
James Mattisfa270db2021-05-31 17:11:10 -07003599 private void enforceManageTestNetworksPermission() {
3600 mContext.enforceCallingOrSelfPermission(
3601 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3602 "ConnectivityService");
3603 }
3604
Junyu Lai71b51532024-02-01 10:39:01 +08003605 @CheckResult
3606 private boolean hasNetworkStackPermission() {
3607 return hasAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_STACK,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003608 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003609 }
3610
Junyu Lai71b51532024-02-01 10:39:01 +08003611 @CheckResult
3612 private boolean hasNetworkStackPermission(int pid, int uid) {
3613 return hasAnyPermissionOf(mContext, pid, uid, android.Manifest.permission.NETWORK_STACK,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003614 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3615 }
3616
Junyu Lai71b51532024-02-01 10:39:01 +08003617 @CheckResult
3618 private boolean hasSystemBarServicePermission(int pid, int uid) {
3619 return hasAnyPermissionOf(mContext, pid, uid,
Quang Anh Luong28eefef2023-11-07 09:43:41 +09003620 android.Manifest.permission.STATUS_BAR_SERVICE);
3621 }
3622
Junyu Lai71b51532024-02-01 10:39:01 +08003623 @CheckResult
3624 private boolean hasNetworkSignalStrengthWakeupPermission(int pid, int uid) {
3625 return hasAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003626 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003627 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3628 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003629 }
3630
Junyu Lai71b51532024-02-01 10:39:01 +08003631 @CheckResult
3632 private boolean hasConnectivityRestrictedNetworksPermission(int callingUid,
Paul Hu8fc2a552022-05-04 18:44:42 +08003633 boolean checkUidsAllowedList) {
Junyu Lai71b51532024-02-01 10:39:01 +08003634 if (hasAnyPermissionOf(mContext,
Paul Hu8fc2a552022-05-04 18:44:42 +08003635 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3636 return true;
3637 }
3638
3639 // fallback to ConnectivityInternalPermission
3640 // TODO: Remove this fallback check after all apps have declared
3641 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
Junyu Lai71b51532024-02-01 10:39:01 +08003642 if (hasAnyPermissionOf(mContext, android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003643 return true;
3644 }
3645
3646 // Check whether uid is in allowed on restricted networks list.
3647 if (checkUidsAllowedList
3648 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3649 return true;
3650 }
3651 return false;
3652 }
3653
3654 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3655 final int callingUid = mDeps.getCallingUid();
Junyu Lai71b51532024-02-01 10:39:01 +08003656 if (!hasConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08003657 throw new SecurityException("ConnectivityService: user " + callingUid
3658 + " has no permission to access restricted network.");
3659 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003660 }
3661
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003662 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003663 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003664 }
3665
Junyu Lai71b51532024-02-01 10:39:01 +08003666 @CheckResult
3667 private boolean hasLocalMacAddressPermission(int pid, int uid) {
Roshan Pius98f59ec2021-02-23 08:47:39 -08003668 return PERMISSION_GRANTED == mContext.checkPermission(
3669 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3670 }
3671
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003672 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003673 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003674 }
3675
3676 private void sendInetConditionBroadcast(NetworkInfo info) {
3677 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3678 }
3679
Wink Saville4f0de1e2011-08-04 15:01:58 -07003680 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003681 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003682 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003683 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003684 if (info.isFailover()) {
3685 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3686 info.setFailover(false);
3687 }
3688 if (info.getReason() != null) {
3689 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3690 }
3691 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003692 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3693 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003694 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003695 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003696 return intent;
3697 }
3698
3699 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3700 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3701 }
3702
Michael Groover73f69482023-01-27 11:01:25 -06003703 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3704 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003705 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3706 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003707 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003708 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003709 if (!mSystemReady
3710 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003711 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003712 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003713 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003714 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003715 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003716 }
3717
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003718 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003719 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003720 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003721 final NetworkInfo ni = intent.getParcelableExtra(
3722 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003723 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3724 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003725 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003726 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003727 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003728 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003729 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003730 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003731 } finally {
3732 Binder.restoreCallingIdentity(ident);
3733 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003734 }
3735 }
3736
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003737 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3738 NetworkInfo info) {
3739 // Delivery group policy APIs are only available on U+.
Chalard Jeandf29a852023-05-29 17:02:43 +09003740 if (!mDeps.isAtLeastU()) return;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003741
3742 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3743 try {
3744 // This allows us to discard older broadcasts still waiting to be delivered
3745 // which have the same namespace and key.
3746 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3747 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3748 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003749 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003750 } catch (UnsupportedApiLevelException e) {
3751 Log.wtf(TAG, "Using unsupported API" + e);
3752 }
3753 }
3754
3755 @VisibleForTesting
3756 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3757 final StringBuilder sb = new StringBuilder();
3758 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3759 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3760 sb.append(info.getExtraInfo());
3761 return sb.toString();
3762 }
3763
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003764 /**
Aaron Huang96011892020-06-27 07:18:23 +08003765 * Called by SystemServer through ConnectivityManager when the system is ready.
3766 */
3767 @Override
3768 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003769 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003770 throw new SecurityException("Calling Uid is not system uid.");
3771 }
3772 systemReadyInternal();
3773 }
3774
3775 /**
3776 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003777 */
3778 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003779 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003780 // Load flags after PackageManager is ready to query module version
3781 mFlags.loadFlags(mDeps, mContext);
3782
Aaron Huang9a57acf2020-12-08 10:03:29 +08003783 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3784 // listening network request which is sent by MultipathPolicyTracker won't be added
3785 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3786 // be called after PermissionMonitor#startMonitoring().
3787 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3788 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3789 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003790 final ConditionVariable startMonitoringDone = new ConditionVariable();
3791 mHandler.post(() -> {
3792 mPermissionMonitor.startMonitoring();
3793 startMonitoringDone.open();
3794 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003795 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003796 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003797
Hugo Benichie5220992017-04-26 14:53:28 +09003798 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003799 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003800 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003801 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003802 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003803 }
3804 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003805
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003806 // Create network requests for always-on networks.
3807 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003808
3809 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003810 // Note that updating can be skipped here if the list is empty only because no uid
3811 // rules are applied before system ready. Normally, the empty uid list means to clear
3812 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003813 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3814 updateMobileDataPreferredUids();
3815 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003816
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +00003817 if (mSatelliteAccessController != null) {
3818 mSatelliteAccessController.start();
3819 }
3820
Motomu Utsumi166f9662022-09-01 10:35:29 +09003821 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
Chalard Jeandf29a852023-05-29 17:02:43 +09003822 if (mDeps.isAtLeastT()) {
Motomu Utsumi166f9662022-09-01 10:35:29 +09003823 mBpfNetMaps.setPullAtomCallback(mContext);
3824 }
Chalard Jeanf95e2de2023-08-22 19:07:47 +09003825 ConnectivitySampleMetricsHelper.start(mContext, mHandler,
3826 CONNECTIVITY_STATE_SAMPLE, this::sampleConnectivityStateToStatsEvent);
Paul Hu3c8c8102022-08-25 07:06:16 +00003827 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3828 // have permission problem. While CV#block() is unbounded in time and can in principle block
3829 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3830 // could have blocked forever too.
3831 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003832 }
3833
The Android Open Source Project28527d22009-03-03 19:31:44 -08003834 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003835 * Start listening for default data network activity state changes.
3836 */
3837 @Override
3838 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003839 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003840 }
3841
3842 /**
3843 * Stop listening for default data network activity state changes.
3844 */
3845 @Override
3846 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003847 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003848 }
3849
3850 /**
3851 * Check whether the default network radio is currently active.
3852 */
3853 @Override
3854 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003855 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003856 }
3857
3858 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003859 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003860 * and set it on it's iface.
3861 */
Junyu Lai970963e2022-10-25 15:46:47 +08003862 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003863 final String iface = newLp.getInterfaceName();
3864 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003865 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003866 // Silently ignore unset MTU value.
3867 return;
3868 }
Hansen Kurli04252032022-12-07 11:21:49 +00003869 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3870 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3871 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003872 return;
3873 }
Hansen Kurli04252032022-12-07 11:21:49 +00003874 // Cannot set MTU without interface name
3875 if (TextUtils.isEmpty(iface)) {
3876 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003877 return;
3878 }
sy.yun4aa73922013-09-02 05:24:09 +09003879
Hansen Kurli04252032022-12-07 11:21:49 +00003880 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3881 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003882 return;
3883 }
3884
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003885 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003886 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003887 mNetd.interfaceSetMtu(iface, mtu);
3888 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003889 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003890 }
3891 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003892
Chenbo Feng15416292018-11-08 17:36:21 -08003893 @VisibleForTesting
3894 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003895
Junyu Lai970963e2022-10-25 15:46:47 +08003896 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003897 String[] values = null;
3898 if (tcpBufferSizes != null) {
3899 values = tcpBufferSizes.split(",");
3900 }
3901
3902 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003903 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003904 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3905 values = tcpBufferSizes.split(",");
3906 }
3907
3908 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3909
3910 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003911 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003912
Chenbo Feng15416292018-11-08 17:36:21 -08003913 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3914 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3915 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003916 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003917 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003918 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003919 }
3920 }
3921
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003922 @Override
3923 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003924 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003925 NETWORK_RESTORE_DELAY_PROP_NAME);
3926 if(restoreDefaultNetworkDelayStr != null &&
3927 restoreDefaultNetworkDelayStr.length() != 0) {
3928 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003929 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003930 } catch (NumberFormatException e) {
3931 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003932 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003933 // if the system property isn't set, use the value for the apn type
3934 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3935
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003936 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3937 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003938 }
3939 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003940 }
3941
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003942 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003943 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003944 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003945 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003946 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003947 // Start gathering diagnostic information.
3948 netDiags.add(new NetworkDiagnostics(
3949 nai.network,
3950 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003951 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003952 DIAG_TIME_MS));
3953 }
3954
3955 for (NetworkDiagnostics netDiag : netDiags) {
3956 pw.println();
3957 netDiag.waitForMeasurements();
3958 netDiag.dump(pw);
3959 }
3960 }
3961
The Android Open Source Project28527d22009-03-03 19:31:44 -08003962 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003963 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3964 @Nullable String[] args) {
Junyu Lai71b51532024-02-01 10:39:01 +08003965 if (!hasDumpPermission(mContext, TAG, writer)) return;
Chiachang Wanga101f852021-04-19 10:59:24 +08003966
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003967 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003968 }
3969
Junyu Lai71b51532024-02-01 10:39:01 +08003970 @CheckResult
3971 private boolean hasDumpPermission(Context context, String tag, PrintWriter pw) {
lucaslin99473f62020-12-10 15:10:54 +08003972 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3973 != PackageManager.PERMISSION_GRANTED) {
3974 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003975 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003976 + " due to missing android.permission.DUMP permission");
3977 return false;
3978 } else {
3979 return true;
3980 }
3981 }
3982
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003983 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003984 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003985
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003986 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003987 dumpNetworkDiagnostics(pw);
3988 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003989 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003990 dumpNetworks(pw);
3991 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003992 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003993 dumpNetworkRequests(pw);
3994 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003995 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3996 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3997 dumpTrafficController(pw, fd, verbose);
3998 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003999 }
Erik Kline9647f382015-06-05 17:47:34 +09004000
Junyu Lai0da479b2022-04-20 15:06:29 +08004001 pw.println("NetworkProviders for:");
4002 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09004003 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08004004 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004005 }
Junyu Lai0da479b2022-04-20 15:06:29 +08004006 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07004007 pw.println();
4008
Chalard Jean5b409c72021-02-04 13:12:59 +09004009 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004010 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09004011 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004012 pw.println("none");
4013 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09004014 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08004015 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08004016 pw.println();
4017
James Mattis8b298a02021-06-01 22:34:04 -07004018 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08004019 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07004020 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08004021 pw.decreaseIndent();
4022 pw.println();
4023
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004024 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004025 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004026 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004027 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004028 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08004029
junyulaif2c67e42018-08-07 19:50:45 +08004030 pw.println("Status for known UIDs:");
4031 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00004032 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08004033 for (int i = 0; i < size; i++) {
4034 // Don't crash if the array is modified while dumping in bugreports.
4035 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00004036 final int uid = mUidBlockedReasons.keyAt(i);
4037 final int blockedReasons = mUidBlockedReasons.valueAt(i);
4038 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00004039 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08004040 } catch (ArrayIndexOutOfBoundsException e) {
4041 pw.println(" ArrayIndexOutOfBoundsException");
4042 } catch (ConcurrentModificationException e) {
4043 pw.println(" ConcurrentModificationException");
4044 }
4045 }
4046 pw.println();
4047 pw.decreaseIndent();
4048
Robert Greenwalta6d85c82014-05-13 15:36:27 -07004049 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004050 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004051 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07004052 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004053 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08004054
Junyu Lai0da479b2022-04-20 15:06:29 +08004055 pw.println("Network Offers:");
4056 pw.increaseIndent();
4057 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
4058 pw.println(offerInfo.offer);
4059 }
4060 pw.decreaseIndent();
4061 pw.println();
4062
Robert Greenwalt94e22142014-07-30 16:31:24 -07004063 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07004064
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004065 pw.println();
markchien5e866652019-09-30 14:40:57 +08004066 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07004067
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004068 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09004069 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09004070
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004071 pw.println();
Motomu Utsumi188bfd32023-05-30 14:38:04 +09004072 dumpCloseFrozenAppSockets(pw);
4073
4074 pw.println();
Junyu Lai155760b2023-10-05 14:51:00 +08004075 dumpBpfProgramStatus(pw);
4076
Chalard Jean53017782022-11-24 17:13:44 +09004077 if (null != mCarrierPrivilegeAuthenticator) {
4078 pw.println();
4079 mCarrierPrivilegeAuthenticator.dump(pw);
4080 }
4081
Junyu Lai155760b2023-10-05 14:51:00 +08004082 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09004083
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09004084 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004085 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09004086 pw.println("mNetworkRequestInfoLogs (most recent first):");
4087 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004088 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09004089 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09004090
4091 pw.println();
4092 pw.println("mNetworkInfoBlockingLogs (most recent first):");
4093 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004094 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09004095 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09004096
4097 pw.println();
4098 pw.println("NetTransition WakeLock activity (most recent first):");
4099 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09004100 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
4101 pw.println("total releases: " + mTotalWakelockReleases);
4102 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
4103 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
4104 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
4105 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
4106 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
4107 }
James Mattiscb1e0362021-04-06 17:07:42 -07004108 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004109
4110 pw.println();
4111 pw.println("bandwidth update requests (by uid):");
4112 pw.increaseIndent();
4113 synchronized (mBandwidthRequests) {
4114 for (int i = 0; i < mBandwidthRequests.size(); i++) {
4115 pw.println("[" + mBandwidthRequests.keyAt(i)
4116 + "]: " + mBandwidthRequests.valueAt(i));
4117 }
4118 }
4119 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07004120 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07004121
James Mattiscb1e0362021-04-06 17:07:42 -07004122 pw.println();
4123 pw.println("mOemNetworkPreferencesLogs (most recent first):");
4124 pw.increaseIndent();
4125 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09004126 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07004127 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09004128
4129 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00004130
4131 pw.println();
4132 pw.println("Permission Monitor:");
4133 pw.increaseIndent();
4134 mPermissionMonitor.dump(pw);
4135 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08004136
4137 pw.println();
4138 pw.println("Legacy network activity:");
4139 pw.increaseIndent();
4140 mNetworkActivityTracker.dump(pw);
4141 pw.decreaseIndent();
Yang Sunca537d52024-01-19 12:53:50 +08004142
4143 pw.println();
4144 pw.println("Multicast routing supported: " +
4145 (mMulticastRoutingCoordinatorService != null));
The Android Open Source Project28527d22009-03-03 19:31:44 -08004146 }
4147
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004148 private void dumpNetworks(IndentingPrintWriter pw) {
4149 for (NetworkAgentInfo nai : networksSortedById()) {
4150 pw.println(nai.toString());
4151 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08004152 pw.println("Nat464Xlat:");
4153 pw.increaseIndent();
4154 nai.dumpNat464Xlat(pw);
4155 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004156 pw.println(String.format(
4157 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
4158 nai.numForegroundNetworkRequests(),
4159 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
4160 nai.numBackgroundNetworkRequests(),
4161 nai.numNetworkRequests()));
4162 pw.increaseIndent();
4163 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4164 pw.println(nai.requestAt(i).toString());
4165 }
4166 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004167 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004168 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08004169 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004170 pw.decreaseIndent();
4171 pw.decreaseIndent();
4172 }
4173 }
4174
James Mattis8b298a02021-06-01 22:34:04 -07004175 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
4176 if (!mProfileNetworkPreferences.isEmpty()) {
4177 pw.println("Profile preferences:");
4178 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09004179 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07004180 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08004181 }
James Mattis8b298a02021-06-01 22:34:04 -07004182 if (!mOemNetworkPreferences.isEmpty()) {
4183 pw.println("OEM preferences:");
4184 pw.increaseIndent();
4185 pw.println(mOemNetworkPreferences);
4186 pw.decreaseIndent();
4187 }
4188 if (!mMobileDataPreferredUids.isEmpty()) {
4189 pw.println("Mobile data preferred UIDs:");
4190 pw.increaseIndent();
4191 pw.println(mMobileDataPreferredUids);
4192 pw.decreaseIndent();
4193 }
James Mattis45d81842021-01-10 14:24:24 -08004194
James Mattis8b298a02021-06-01 22:34:04 -07004195 pw.println("Default requests:");
4196 pw.increaseIndent();
4197 dumpPerAppDefaultRequests(pw);
4198 pw.decreaseIndent();
4199 }
4200
4201 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08004202 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
4203 if (mDefaultRequest == defaultRequest) {
4204 continue;
4205 }
4206
James Mattis8b298a02021-06-01 22:34:04 -07004207 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
4208 final String networkOutput;
4209 if (null == satisfier) {
4210 networkOutput = "null";
4211 } else if (mNoServiceNetwork.equals(satisfier)) {
4212 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08004213 } else {
James Mattis8b298a02021-06-01 22:34:04 -07004214 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08004215 }
James Mattis8b298a02021-06-01 22:34:04 -07004216 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
4217 ? "" : " asUid: " + defaultRequest.mAsUid;
4218 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
4219 + defaultRequest.mPid + asUidString + "]";
4220 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
4221 + " Preference order: " + defaultRequest.mPreferenceOrder
4222 + " Tracked UIDs: " + defaultRequest.getUids();
4223 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08004224 }
4225 }
4226
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004227 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08004228 NetworkRequestInfo[] infos = null;
4229 while (infos == null) {
4230 try {
4231 infos = requestsSortedById();
4232 } catch (ConcurrentModificationException e) {
4233 // mNetworkRequests should only be accessed from handler thread, except dump().
4234 // As dump() is never called in normal usage, it would be needlessly expensive
4235 // to lock the collection only for its benefit. Instead, retry getting the
4236 // requests if ConcurrentModificationException is thrown during dump().
4237 }
4238 }
4239 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09004240 pw.println(nri.toString());
4241 }
4242 }
4243
Ken Chene6d511f2022-01-25 11:10:42 +08004244 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
4245 boolean verbose) {
4246 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09004247 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08004248 } catch (ServiceSpecificException e) {
4249 pw.println(e.getMessage());
4250 } catch (IOException e) {
4251 loge("Dump BPF maps failed, " + e);
4252 }
4253 }
4254
Chalard Jean524f0b12021-10-25 21:11:56 +09004255 private void dumpAllRequestInfoLogsToLogcat() {
4256 try (PrintWriter logPw = new PrintWriter(new Writer() {
4257 @Override
4258 public void write(final char[] cbuf, final int off, final int len) {
4259 // This method is called with 0-length and 1-length arrays for empty strings
4260 // or strings containing only the DEL character.
4261 if (len <= 1) return;
4262 Log.e(TAG, new String(cbuf, off, len));
4263 }
4264 @Override public void flush() {}
4265 @Override public void close() {}
4266 })) {
4267 mNetworkRequestInfoLogs.dump(logPw);
4268 }
4269 }
4270
Hugo Benichia480ba52018-09-03 08:19:02 +09004271 /**
4272 * Return an array of all current NetworkAgentInfos sorted by network id.
4273 */
4274 private NetworkAgentInfo[] networksSortedById() {
4275 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004276 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004277 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09004278 return networks;
4279 }
4280
4281 /**
4282 * Return an array of all current NetworkRequest sorted by request id.
4283 */
James Mattis258ea3c2020-11-15 15:04:40 -08004284 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08004285 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09004286 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08004287 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08004288 // Sort the array based off the NRI containing the min requestId in its requests.
4289 Arrays.sort(requests,
4290 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
4291 Comparator.comparingInt(req -> req.requestId)).requestId
4292 )
4293 );
Hugo Benichia480ba52018-09-03 08:19:02 +09004294 return requests;
4295 }
4296
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004297 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08004298 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004299 if (officialNai != null && officialNai.equals(nai)) return true;
4300 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004301 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07004302 " - " + nai);
4303 }
4304 return false;
4305 }
4306
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004307 private boolean isDisconnectRequest(Message msg) {
4308 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
4309 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
4310 return info.getState() == NetworkInfo.State.DISCONNECTED;
4311 }
4312
Robert Greenwalt2034b912009-08-12 16:08:25 -07004313 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004314 private class NetworkStateTrackerHandler extends Handler {
4315 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07004316 super(looper);
4317 }
4318
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004319 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004320 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
4321 final NetworkAgentInfo nai = arg.first;
4322 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004323 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09004324 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004325 }
4326 return;
4327 }
4328
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004329 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09004330 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004331 return;
4332 }
4333
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004334 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004335 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean78c9a382023-10-26 19:53:33 +09004336 final NetworkCapabilities proposed = (NetworkCapabilities) arg.second;
4337 if (!nai.respectsNcStructuralConstraints(proposed)) {
4338 Log.wtf(TAG, "Agent " + nai + " violates nc structural constraints : "
4339 + nai.networkCapabilities + " -> " + proposed);
4340 disconnectAndDestroyNetwork(nai);
4341 return;
4342 }
4343 nai.setDeclaredCapabilities(proposed);
Chalard Jean39b12d42022-02-27 12:08:49 +09004344 final NetworkCapabilities sanitized =
4345 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09004346 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004347 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07004348 break;
4349 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004350 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004351 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09004352 processLinkPropertiesFromAgent(nai, newLp);
4353 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004354 break;
4355 }
4356 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004357 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004358 updateNetworkInfo(nai, info);
4359 break;
4360 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004361 case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
4362 final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
Chalard Jean22350c92023-10-07 19:21:45 +09004363 handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09004364 break;
4365 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004366 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09004367 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07004368 break;
4369 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004370 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09004371 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09004372 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09004373 // Note that if the NAI had been connected, this would affect the
4374 // score, and therefore would require re-mixing the score and performing
4375 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04004376 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004377 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
4378 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08004379 // Mark the network as temporarily accepting partial connectivity so that it
4380 // will be validated (and possibly become default) even if it only provides
4381 // partial internet access. Note that if user connects to partial connectivity
4382 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
4383 // out of wifi coverage) and if the same wifi is available again, the device
4384 // will auto connect to this wifi even though the wifi has "no internet".
4385 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004386 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07004387 break;
4388 }
junyulai011b1f12019-01-03 18:50:15 +08004389 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004390 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09004391 break;
4392 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004393 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09004394 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09004395 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09004396
4397 if (isLegacyLockdownNai(nai)
4398 && (underlying == null || underlying.size() != 1)) {
4399 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
4400 + " must have exactly one underlying network: " + underlying);
4401 }
4402
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004403 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
4404 nai.declaredUnderlyingNetworks = (underlying != null)
4405 ? underlying.toArray(new Network[0]) : null;
4406
4407 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
4408 if (DBG) {
4409 log(nai.toShortString() + " changed underlying networks to "
4410 + Arrays.toString(nai.declaredUnderlyingNetworks));
4411 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004412 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004413 notifyIfacesChangedForNetworkStats();
4414 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07004415 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09004416 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004417 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
4418 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4419 nai.teardownDelayMs = msg.arg1;
4420 } else {
4421 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
4422 }
Chalard Jean550b5212021-03-05 23:07:53 +09004423 break;
4424 }
4425 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
4426 nai.setLingerDuration((int) arg.second);
4427 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004428 }
Tyler Wear72388212021-09-09 14:49:02 -07004429 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
4430 DscpPolicy policy = (DscpPolicy) arg.second;
4431 if (mDscpPolicyTracker != null) {
4432 mDscpPolicyTracker.addDscpPolicy(nai, policy);
4433 }
4434 break;
4435 }
4436 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
4437 if (mDscpPolicyTracker != null) {
4438 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
4439 }
4440 break;
4441 }
4442 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
4443 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004444 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07004445 }
4446 break;
4447 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004448 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09004449 if (!nai.everConnected()) {
4450 Log.d(TAG, "unregisterAfterReplacement on never-connected "
4451 + nai.toShortString() + ", tearing down instead");
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09004452 teardownUnneededNetwork(nai);
4453 break;
4454 }
4455
4456 if (nai.isDestroyed()) {
4457 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
4458 + ", ignoring");
4459 break;
4460 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004461
4462 final int timeoutMs = (int) arg.second;
4463 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
4464 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
4465 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
4466 }
4467
4468 // Marking a network awaiting replacement is used to ensure that any requests
4469 // satisfied by the network do not switch to another network until a
4470 // replacement is available or the wait for a replacement times out.
4471 // If the network is inactive (i.e., nascent or lingering), then there are no
4472 // such requests, and there is no point keeping it. Just tear it down.
4473 // Note that setLingerDuration(0) cannot be used to do this because the network
4474 // could be nascent.
4475 nai.clearInactivityState();
4476 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4477 Log.d(TAG, nai.toShortString()
4478 + " marked awaiting replacement is unneeded, tearing down instead");
4479 teardownUnneededNetwork(nai);
4480 break;
4481 }
4482
4483 Log.d(TAG, "Marking " + nai.toShortString()
4484 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
4485 destroyNativeNetwork(nai);
4486
4487 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
4488 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
4489 // consider the fact that the network could already have disconnected or been
4490 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
4491 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
4492 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
4493 mKeepaliveTracker.handleStopAllKeepalives(nai,
4494 SocketKeepalive.ERROR_INVALID_NETWORK);
4495
4496 nai.updateScoreForNetworkAgentUpdate();
4497 // This rematch is almost certainly not going to result in any changes, because
4498 // the destroyed flag is only just above the "current satisfier wins"
4499 // tie-breaker. But technically anything that affects scoring should rematch.
4500 rematchAllNetworksAndRequests();
Jean Chalard3160bc02023-06-27 08:54:23 +00004501 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004502 break;
4503 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004504 }
4505 }
4506
4507 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004508 final int netId = msg.arg2;
4509 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004510 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09004511 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004512 switch (msg.what) {
4513 default:
4514 return false;
lucasline117e2e2019-10-22 18:27:33 +08004515 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08004516 if (nai == null) {
4517 break;
4518 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004519 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
4520 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08004521 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004522 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08004523 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004524 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08004525 if (probePrivateDnsCompleted) {
4526 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
4527 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004528 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08004529 }
4530 // Only show the notification when the private DNS is broken and the
4531 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004532 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08004533 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
4534 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004535 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08004536 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
4537 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
4538 // private DNS is broken, it means this network is being reevaluated.
4539 // Either probing private DNS is not necessary any more or it hasn't been
4540 // done yet. In either case, the networkCapabilities should be updated to
4541 // reflect the new status.
4542 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004543 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004544 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08004545 }
4546 break;
4547 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004548 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004549 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
4550
Erik Kline31b4a9e2018-01-11 21:07:29 +09004551 if (nai == null) break;
4552
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004553 handleNetworkTested(nai, results.mTestResult,
4554 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004555 break;
4556 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004557 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09004558 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07004559 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04004560 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08004561 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08004562 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08004563 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
4564 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04004565 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04004566 if (nai == null) {
4567 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
4568 break;
4569 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004570 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09004571 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09004572 (PendingIntent) msg.obj,
4573 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07004574 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004575 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04004576 break;
4577 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004578 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09004579 if (nai == null) break;
4580
Erik Kline9a62f012018-03-21 07:18:33 -07004581 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09004582 break;
4583 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004584 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004585 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08004586 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004587 break;
4588 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004589 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004590 return true;
4591 }
4592
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004593 private void handleNetworkTested(
4594 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09004595 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
4596 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09004597 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004598
4599 // If there is any kind of working networking, then the NAI has been evaluated
4600 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
4601 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09004602 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004603 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09004604 // Because of b/245893397, if the score is updated when updateCapabilities is called,
4605 // any callback that receives onAvailable for that rematch receives an extra caps
4606 // callback. To prevent that, update the score in the agent so the updates below won't
4607 // see an update to both caps and score at the same time.
4608 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004609 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
4610
he_won.hwang881307a2022-03-15 21:23:52 +09004611 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
4612 // Assume the validation failure is due to a temporary failure after roaming
4613 // and ignore it. NetworkMonitor will continue to retry validation. If it
4614 // continues to fail after the block timeout expires, the network will be
4615 // marked unvalidated. If it succeeds, then validation state will not change.
4616 return;
4617 }
4618
Chalard Jean254bd162022-08-25 13:04:51 +09004619 final boolean wasValidated = nai.isValidated();
4620 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09004621 final boolean wasPortal = nai.captivePortalDetected();
4622 nai.setPartialConnectivity(partial);
4623 nai.setCaptivePortalDetected(portal);
4624 nai.updateScoreForNetworkAgentUpdate();
4625 final boolean partialConnectivityChanged = (wasPartial != partial);
4626 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004627
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004628 if (DBG) {
4629 final String logMsg = !TextUtils.isEmpty(redirectUrl)
4630 ? " with redirect to " + redirectUrl
4631 : "";
Chalard Jean49707572019-12-10 21:07:02 +09004632 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004633 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09004634 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004635 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004636 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004637 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004638 if (valid) {
4639 handleFreshlyValidatedNetwork(nai);
4640 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4641 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004642 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004643 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004644 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004645 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004646 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004647 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004648 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004649 NotificationType.PRIVATE_DNS_BROKEN);
4650 // If network becomes valid, the hasShownBroken should be reset for
4651 // that network so that the notification will be fired when the private
4652 // DNS is broken again.
4653 nai.networkAgentConfig.hasShownBroken = false;
4654 }
4655 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004656 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004657 } else if (portalChanged) {
4658 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004659 == getCaptivePortalMode(nai)) {
Chalard Jean8a9061f2022-09-22 16:25:10 +09004660 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4661 nai.onPreventAutomaticReconnect();
4662 teardownUnneededNetwork(nai);
4663 return;
4664 } else {
4665 updateCapabilitiesForNetwork(nai);
4666 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004667 } else if (becameEvaluated) {
4668 // If valid or partial connectivity changed, updateCapabilities* has
4669 // done the rematch.
4670 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004671 }
4672 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004673
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004674 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004675 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004676 nai.onValidationStatusChanged(
4677 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4678 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004679
4680 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004681 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004682 // immediately. Re-notify partial connectivity silently if no internet
4683 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004684 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004685 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004686 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4687 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004688 }
4689
Chalard Jean254bd162022-08-25 13:04:51 +09004690 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004691 handleNetworkUnvalidated(nai);
4692 }
4693 }
4694
Andriy Naborskyyd032dd42023-09-26 02:03:18 +00004695 private int getCaptivePortalMode(@NonNull NetworkAgentInfo nai) {
4696 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) &&
4697 mContext.getPackageManager().hasSystemFeature(FEATURE_WATCH)) {
4698 // Do not avoid captive portal when network is wear proxy.
4699 return ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT;
4700 }
4701
Calvin Ondada1452016-10-11 15:10:46 -07004702 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004703 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4704 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004705 }
4706
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004707 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4708 switch (msg.what) {
4709 default:
4710 return false;
4711 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4712 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4713 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4714 handleLingerComplete(nai);
4715 }
4716 break;
4717 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004718 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4719 handleNetworkAgentRegistered(msg);
4720 break;
4721 }
4722 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4723 handleNetworkAgentDisconnected(msg);
4724 break;
4725 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004726 }
4727 return true;
4728 }
4729
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004730 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004731 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004732 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004733 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004734 maybeHandleNetworkAgentMessage(msg);
4735 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004736 }
4737 }
4738
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004739 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004740 private final int mNetId;
4741 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004742
4743 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004744 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004745 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004746 }
4747
4748 @Override
4749 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4750 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004751 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004752 }
4753
4754 @Override
4755 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004756 // Legacy version of notifyNetworkTestedWithExtras.
4757 // Would only be called if the system has a NetworkStack module older than the
4758 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004759 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004760 }
4761
4762 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004763 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004764 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4765 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004766 final Message msg = mTrackerHandler.obtainMessage(
4767 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004768 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004769 new NetworkTestedResults(
4770 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004771 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004772
4773 // Invoke ConnectivityReport generation for this Network test event.
4774 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4775 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004776
Cody Kestingf1120be2020-08-03 18:01:40 -07004777 // NetworkMonitor reports the network validation result as a bitmask while
4778 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4779 // logical value for ConnectivityDiagnostics.
4780 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4781 p.result);
4782
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004783 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004784 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004785 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4786 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4787
Aaron Huang959d3642021-01-21 15:47:41 +08004788 ConnectivityReportEvent reportEvent =
4789 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4790 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004791 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004792 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004793 }
4794
4795 @Override
4796 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4797 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4798 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004799 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004800 }
4801
4802 @Override
lucasline117e2e2019-10-22 18:27:33 +08004803 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4804 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4805 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004806 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004807 }
4808
4809 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004810 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4811 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4812 EVENT_CAPPORT_DATA_CHANGED,
4813 0, mNetId, data));
4814 }
4815
4816 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004817 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004818 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004819 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004820
4821 final PendingIntent pendingIntent;
4822 // Only the system server can register notifications with package "android"
4823 final long token = Binder.clearCallingIdentity();
4824 try {
paulhu7746e4e2020-06-09 19:07:03 +08004825 pendingIntent = PendingIntent.getBroadcast(
4826 mContext,
4827 0 /* requestCode */,
4828 intent,
4829 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004830 } finally {
4831 Binder.restoreCallingIdentity(token);
4832 }
4833 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4834 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004835 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004836 }
4837
4838 @Override
4839 public void hideProvisioningNotification() {
4840 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004841 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004842 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004843
4844 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004845 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004846 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004847 }
4848
4849 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004850 public int getInterfaceVersion() {
4851 return this.VERSION;
4852 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004853
4854 @Override
4855 public String getInterfaceHash() {
4856 return this.HASH;
4857 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004858 }
4859
Cody Kestingf1120be2020-08-03 18:01:40 -07004860 /**
4861 * Converts the given NetworkMonitor-specific validation result bitmask to a
4862 * ConnectivityDiagnostics-specific validation result int.
4863 */
4864 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4865 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4866 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4867 }
4868 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4869 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4870 }
4871 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4872 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4873 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4874 }
4875
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004876 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004877 log("Data stall detected with methods: " + p.detectionMethod);
4878
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004879 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004880 int detectionMethod = 0;
4881 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4882 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4883 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4884 }
4885 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4886 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4887 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4888 p.tcpMetricsCollectionPeriodMillis);
4889 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004890 }
4891
Cody Kestingf53a0752020-04-15 12:33:28 -07004892 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004893 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004894 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004895
4896 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4897 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4898 // the cost of going through two handlers.
4899 mConnectivityDiagnosticsHandler.sendMessage(msg);
4900 }
4901
Cody Kestingb37958e2020-05-15 10:36:01 -07004902 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4903 return (p.detectionMethod & detectionMethod) != 0;
4904 }
4905
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004906 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4907 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004908 }
4909
Erik Klinea73af002018-06-26 18:53:43 +09004910 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4911 if (nai == null) return;
4912 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4913 // in order to restart a validation pass from within netd.
4914 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
Mike Yu9738b472023-11-22 02:18:19 +00004915 if (cfg.inOpportunisticMode()) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004916 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004917 }
4918 }
4919
Erik Kline31b4a9e2018-01-11 21:07:29 +09004920 private void handlePrivateDnsSettingsChanged() {
4921 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4922
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004923 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004924 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004925 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004926 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4927 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004928 }
4929 }
4930
Erik Kline9a62f012018-03-21 07:18:33 -07004931 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4932 // Private DNS only ever applies to networks that might provide
4933 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004934 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004935
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004936 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004937 // schedule DNS resolutions. If a DNS resolution is required the
4938 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004939 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004940
4941 // With Private DNS bypass support, we can proceed to update the
4942 // Private DNS config immediately, even if we're in strict mode
4943 // and have not yet resolved the provider name into a set of IPs.
4944 updatePrivateDns(nai, cfg);
4945 }
4946
4947 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4948 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004949 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004950 }
4951
dalyk1720e542018-03-05 12:42:22 -05004952 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4953 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4954 if (nai == null) {
4955 return;
4956 }
4957 mDnsManager.updatePrivateDnsValidation(update);
4958 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4959 }
4960
paulhu7c0a2e62021-01-08 00:51:49 +08004961 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004962 int prefixLength) {
4963 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4964 if (nai == null) return;
4965
paulhu7c0a2e62021-01-08 00:51:49 +08004966 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4967 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004968
4969 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004970 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004971 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004972 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004973 prefixLength);
4974 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004975 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004976 return;
4977 }
4978 }
4979
Lorenzo Colittid523d142020-04-01 20:16:30 +09004980 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004981 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4982 }
4983
Hai Shalome58bdc62021-01-11 18:45:34 -08004984 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004985 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004986 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004987 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4988 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4989 }
4990
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004991 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004992 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004993 * @param nai the agent info to update
4994 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004995 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004996 */
junyulai2b6f0c22021-02-03 20:15:30 +08004997 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4998 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4999 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005000 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08005001 // one lingered request, set inactive.
5002 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08005003 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08005004 if (DBG) log("Unsetting inactive " + nai.toShortString());
5005 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005006 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08005007 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005008 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08005009 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
5010 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005011 }
junyulai2b6f0c22021-02-03 20:15:30 +08005012 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005013 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005014 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09005015 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09005016 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05005017 }
5018
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005019 private void handleNetworkAgentRegistered(Message msg) {
5020 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
5021 if (!mNetworkAgentInfos.contains(nai)) {
5022 return;
5023 }
5024
5025 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
5026 if (VDBG) log("NetworkAgent registered");
5027 } else {
5028 loge("Error connecting NetworkAgent");
5029 mNetworkAgentInfos.remove(nai);
5030 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005031 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005032 synchronized (mNetworkForNetId) {
5033 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005034 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005035 mNetIdManager.releaseNetId(nai.network.getNetId());
5036 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09005037 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005038 }
5039 }
5040 }
Paul Jensend5f53392014-11-25 15:26:53 -05005041
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005042 @VisibleForTesting
5043 protected static boolean shouldCreateNetworksImmediately() {
Chalard Jeana16607f2023-06-27 19:16:00 +09005044 // The feature of creating the networks immediately was slated for U, but race conditions
5045 // detected late required this was flagged off.
5046 // TODO : enable this in a Mainline update or in V, and re-enable the test for this
5047 // in NetworkAgentTest.
5048 return false;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005049 }
5050
5051 private static boolean shouldCreateNativeNetwork(@NonNull NetworkAgentInfo nai,
5052 @NonNull NetworkInfo.State state) {
5053 if (nai.isCreated()) return false;
5054 if (state == NetworkInfo.State.CONNECTED) return true;
5055 if (state != NetworkInfo.State.CONNECTING) {
5056 // TODO: throw if no WTFs are observed in the field.
Lorenzo Colitti233f2d12023-06-07 11:34:05 +09005057 if (shouldCreateNetworksImmediately()) {
5058 Log.wtf(TAG, "Uncreated network in invalid state: " + state);
5059 }
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09005060 return false;
5061 }
5062 return nai.isVPN() || shouldCreateNetworksImmediately();
5063 }
5064
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005065 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09005066 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005067 }
5068
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005069 @VisibleForTesting
5070 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09005071 // T+ devices should use unregisterAfterReplacement.
Chalard Jeandf29a852023-05-29 17:02:43 +09005072 if (mDeps.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005073
5074 // If the network never roamed, return false. The check below is not sufficient if time
5075 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
5076 if (nai.lastRoamTime == 0) return false;
5077
he_won.hwang881307a2022-03-15 21:23:52 +09005078 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
5079 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09005080 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09005081 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09005082 final long currentTimeMs = SystemClock.elapsedRealtime();
5083 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09005084 if (timeSinceLastRoam <= blockTimeOut) {
5085 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
5086 return true;
5087 }
5088 }
5089 return false;
5090 }
5091
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005092 private void handleNetworkAgentDisconnected(Message msg) {
5093 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07005094 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005095 }
5096
Chalard Jeand9fffc32018-05-11 20:19:20 +09005097 // Destroys a network, remove references to it from the internal state managed by
5098 // ConnectivityService, free its interfaces and clean up.
5099 // Must be called on the Handler thread.
5100 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005101 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07005102
5103 if (!mNetworkAgentInfos.contains(nai)) return;
5104
Chalard Jeand9fffc32018-05-11 20:19:20 +09005105 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09005106 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005107 }
lucaslinb25c9a62019-02-12 15:30:13 +08005108 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005109 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005110 // A network agent has disconnected.
5111 // TODO - if we move the logic to the network agent (have them disconnect
5112 // because they lost all their requests or because their score isn't good)
5113 // then they would disconnect organically, report their new state and then
5114 // disconnect the channel.
wangshengrjxtjcbfd5d3d92023-05-09 09:51:06 +08005115 if (nai.networkInfo.isConnected() || nai.networkInfo.isSuspended()) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005116 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
5117 null, null);
5118 }
Chalard Jean5b409c72021-02-04 13:12:59 +09005119 final boolean wasDefault = isDefaultNetwork(nai);
5120 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005121 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09005122 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005123 if (mTrackMultiNetworkActivities) {
5124 // If trackMultiNetworkActivities is disabled, ActivityTracker removes idleTimer when
5125 // the network becomes no longer the default network.
5126 mNetworkActivityTracker.removeDataActivityTracking(nai);
5127 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005128 notifyIfacesChangedForNetworkStats();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005129 // If this was a local network forwarded to some upstream, or if some local network was
5130 // forwarded to this nai, then disable forwarding rules now.
Chalard Jean22350c92023-10-07 19:21:45 +09005131 maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005132 // If this is a local network with an upstream selector, remove the associated network
5133 // request.
5134 if (nai.isLocalNetwork()) {
5135 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
5136 if (null != selector) {
5137 handleRemoveNetworkRequest(mNetworkRequests.get(selector));
5138 }
5139 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005140 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
5141 // by other networks that are already connected. Perhaps that can be done by
5142 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
5143 // of rematchAllNetworksAndRequests
5144 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08005145 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07005146
5147 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005148 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
5149 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08005150 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09005151 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005152 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005153 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09005154 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005155 synchronized (mNetworkForNetId) {
5156 // Remove the NetworkAgent, but don't mark the netId as
5157 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08005158 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005159 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09005160 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08005161 // Update allowed network lists in netd. This should be called after removing nai
5162 // from mNetworkAgentInfos.
5163 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005164 // Remove all previously satisfied requests.
5165 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005166 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09005167 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08005168 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08005169 if (currentNetwork != null
5170 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08005171 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09005172 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
5173 // rematch not to keep disconnected agents instead of setting it here ; this
5174 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08005175 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09005176 for (final NetworkOfferInfo noi : mNetworkOffers) {
5177 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08005178 }
James Mattise3ef1912020-12-20 11:09:58 -08005179
Chalard Jean5b409c72021-02-04 13:12:59 +09005180 if (mDefaultRequest == nri) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09005181 mNetworkActivityTracker.updateDefaultNetwork(null /* newNetwork */, nai);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09005182 maybeClosePendingFrozenSockets(null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08005183 ensureNetworkTransitionWakelock(nai.toShortString());
5184 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09005185 }
5186 }
junyulai2b6f0c22021-02-03 20:15:30 +08005187 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08005188 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09005189 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08005190 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09005191 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005192 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005193 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005194
Aaron Huang9fe47be2021-06-08 13:11:45 +08005195 if (null == getDefaultNetwork() && nai.linkProperties.getHttpProxy() != null) {
5196 // The obvious place to do this would be in makeDefault(), however makeDefault() is
5197 // not called by the rematch in this case. This is because the code above unset
5198 // this network from the default request's satisfier, and that is what the rematch
5199 // is using as its source data to know what the old satisfier was. So as far as the
5200 // rematch above is concerned, the old default network was null.
5201 // Therefore if there is no new default, the default network was null and is still
5202 // null, thus there was no change so makeDefault() is not called. So if the old
5203 // network had a proxy and there is no new default, the proxy tracker should be told
5204 // that there is no longer a default proxy.
5205 // Strictly speaking this is not essential because having a proxy setting when
5206 // there is no network is harmless, but it's still counter-intuitive so reset to null.
5207 mProxyTracker.setDefaultProxy(null);
5208 }
5209
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005210 // Immediate teardown.
5211 if (nai.teardownDelayMs == 0) {
5212 destroyNetwork(nai);
5213 return;
5214 }
5215
5216 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09005217 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05305218 try {
5219 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
5220 } catch (RemoteException e) {
5221 Log.d(TAG, "Error marking network restricted during teardown: ", e);
5222 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09005223 }
5224 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
5225 }
5226
5227 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005228 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09005229 // Tell netd to clean up the configuration for this network
5230 // (routing rules, DNS, etc).
5231 // This may be slow as it requires a lot of netd shelling out to ip and
5232 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09005233 // after we've rematched networks with requests (which might change the default
5234 // network or service a new request from an app), so network traffic isn't interrupted
5235 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08005236 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005237 }
Chalard Jeandf29a852023-05-29 17:02:43 +09005238 if (!nai.isCreated() && !mDeps.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005239 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
5240 // This can never run if the code above runs because shouldDestroyNativeNetwork is
5241 // false if the network was never created.
5242 // TODO: delete when S is no longer supported.
5243 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09005244 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08005245 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09005246 }
5247
Chalard Jean1e4c2182023-10-06 18:45:53 +09005248 private void maybeDisableForwardRulesForDisconnectingNai(
Chalard Jean22350c92023-10-07 19:21:45 +09005249 @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
Chalard Jean1e4c2182023-10-06 18:45:53 +09005250 // Step 1 : maybe this network was the upstream for one or more local networks.
5251 for (final NetworkAgentInfo local : mNetworkAgentInfos) {
5252 if (!local.isLocalNetwork()) continue;
5253 final NetworkRequest selector = local.localNetworkConfig.getUpstreamSelector();
5254 if (null == selector) continue;
5255 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5256 // null == nri can happen while disconnecting a network, because destroyNetwork() is
5257 // called after removing all associated NRIs from mNetworkRequests.
5258 if (null == nri) continue;
5259 final NetworkAgentInfo satisfier = nri.getSatisfier();
5260 if (disconnecting != satisfier) continue;
5261 removeLocalNetworkUpstream(local, disconnecting);
Chalard Jean22350c92023-10-07 19:21:45 +09005262 // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
5263 // correctly contains null as an upstream.
5264 if (sendCallbacks) {
5265 nri.setSatisfier(null, null);
5266 notifyNetworkCallbacks(local,
5267 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
5268 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005269 }
5270
5271 // Step 2 : maybe this is a local network that had an upstream.
5272 if (!disconnecting.isLocalNetwork()) return;
5273 final NetworkRequest selector = disconnecting.localNetworkConfig.getUpstreamSelector();
5274 if (null == selector) return;
5275 final NetworkRequestInfo nri = mNetworkRequests.get(selector);
5276 // As above null == nri can happen while disconnecting a network, because destroyNetwork()
5277 // is called after removing all associated NRIs from mNetworkRequests.
5278 if (null == nri) return;
5279 final NetworkAgentInfo satisfier = nri.getSatisfier();
5280 if (null == satisfier) return;
5281 removeLocalNetworkUpstream(disconnecting, satisfier);
5282 }
5283
5284 private void removeLocalNetworkUpstream(@NonNull final NetworkAgentInfo localAgent,
5285 @NonNull final NetworkAgentInfo upstream) {
5286 try {
Yang Sun29037f62023-12-04 10:31:58 +08005287 final String localNetworkInterfaceName = localAgent.linkProperties.getInterfaceName();
5288 final String upstreamNetworkInterfaceName = upstream.linkProperties.getInterfaceName();
Chalard Jean1e4c2182023-10-06 18:45:53 +09005289 mRoutingCoordinatorService.removeInterfaceForward(
Yang Sun29037f62023-12-04 10:31:58 +08005290 localNetworkInterfaceName,
5291 upstreamNetworkInterfaceName);
5292 disableMulticastRouting(localNetworkInterfaceName, upstreamNetworkInterfaceName);
Chalard Jean1e4c2182023-10-06 18:45:53 +09005293 } catch (RemoteException e) {
5294 loge("Couldn't remove interface forward for "
5295 + localAgent.linkProperties.getInterfaceName() + " to "
5296 + upstream.linkProperties.getInterfaceName() + " while disconnecting");
5297 }
5298 }
5299
Ken Chen6df7a902021-04-09 15:08:42 +08005300 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08005301 try {
5302 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08005303 final NativeNetworkConfig config;
5304 if (nai.isVPN()) {
5305 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08005306 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08005307 return false;
5308 }
5309 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
5310 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005311 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08005312 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08005313 } else {
Chalard Jeane0aaca52023-10-17 13:23:07 +09005314 config = new NativeNetworkConfig(nai.network.getNetId(),
Chalard Jean1e4c2182023-10-06 18:45:53 +09005315 nai.isLocalNetwork() ? NativeNetworkType.PHYSICAL_LOCAL
5316 : NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09005317 getNetworkPermission(nai.networkCapabilities),
5318 false /* secure */,
5319 VpnManager.TYPE_VPN_NONE,
5320 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005321 }
Ken Chen6df7a902021-04-09 15:08:42 +08005322 mNetd.networkCreate(config);
5323 mDnsResolver.createNetworkCache(nai.network.getNetId());
Ken Chen6b134f12023-10-07 07:46:47 +08005324 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(),
5325 nai.networkCapabilities);
Luke Huangfdd11f82019-04-09 18:41:49 +08005326 return true;
5327 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08005328 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08005329 return false;
5330 }
5331 }
5332
Ken Chen6df7a902021-04-09 15:08:42 +08005333 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08005334 if (mDscpPolicyTracker != null) {
5335 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
5336 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09005337 // Remove any forwarding rules to and from the interface for this network, since
Chalard Jean22350c92023-10-07 19:21:45 +09005338 // the interface is going to go away. Don't send the callbacks however ; if the network
5339 // was is being disconnected the callbacks have already been sent, and if it is being
5340 // destroyed pending replacement they will be sent when it is disconnected.
5341 maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
Luke Huangfdd11f82019-04-09 18:41:49 +08005342 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005343 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09005344 } catch (RemoteException | ServiceSpecificException e) {
5345 loge("Exception destroying network(networkDestroy): " + e);
5346 }
5347 try {
Ken Chen6df7a902021-04-09 15:08:42 +08005348 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08005349 } catch (RemoteException | ServiceSpecificException e) {
5350 loge("Exception destroying network: " + e);
5351 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005352 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
5353 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
5354 // gets created, could add data to DnsManager data structures that will never get deleted.
5355 mDnsManager.removeNetwork(nai.network);
5356
5357 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09005358 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005359 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
5360 }
5361
Chalard Jean254bd162022-08-25 13:04:51 +09005362 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09005363 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08005364 }
5365
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005366 // If this method proves to be too slow then we can maintain a separate
5367 // pendingIntent => NetworkRequestInfo map.
5368 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
5369 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005370 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
5371 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
5372 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09005373 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005374 return entry.getValue();
5375 }
5376 }
5377 return null;
5378 }
5379
Chalard Jean524f0b12021-10-25 21:11:56 +09005380 private void checkNrisConsistency(final NetworkRequestInfo nri) {
Chalard Jeandf29a852023-05-29 17:02:43 +09005381 if (mDeps.isAtLeastT()) {
Chalard Jean524f0b12021-10-25 21:11:56 +09005382 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
5383 if (n.mBinder != null && n.mBinder == nri.mBinder) {
5384 // Temporary help to debug b/194394697 ; TODO : remove this function when the
5385 // bug is fixed.
5386 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09005387 throw new IllegalStateException("This NRI is already registered. New : " + nri
5388 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09005389 }
5390 }
5391 }
5392 }
5393
Chalard Jeanac9ace02022-01-26 16:54:05 +09005394 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
5395 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08005396 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jean8c63ed82023-11-09 15:26:48 +09005397 return mCarrierPrivilegeAuthenticator.isCarrierServiceUidForNetworkCapabilities(
Chalard Jeanac9ace02022-01-26 16:54:05 +09005398 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005399 }
5400 return false;
5401 }
5402
James Mattisf7027322020-12-13 16:28:14 -08005403 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005404 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08005405 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
5406 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
5407 final NetworkRequestInfo existingRequest =
5408 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005409 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08005410 if (DBG) {
5411 log("Replacing " + existingRequest.mRequests.get(0) + " with "
5412 + nri.mRequests.get(0) + " because their intents matched.");
5413 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09005414 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08005415 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005416 }
Erik Kline05f2b402015-04-30 12:58:40 +09005417 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005418 }
5419
James Mattisf7027322020-12-13 16:28:14 -08005420 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005421 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08005422 }
5423
James Mattis3ce3d3c2021-02-09 18:18:28 -08005424 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005425 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08005426 for (final NetworkRequestInfo nri : nris) {
5427 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005428 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08005429 for (final NetworkRequest req : nri.mRequests) {
5430 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08005431 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08005432 if (req.isListen()) {
5433 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
5434 if (req.networkCapabilities.hasSignalStrength()
5435 && network.satisfiesImmutableCapabilitiesOf(req)) {
5436 updateSignalStrengthThresholds(network, "REGISTER", req);
5437 }
James Mattisf7027322020-12-13 16:28:14 -08005438 }
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005439 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5440 mNetworkRequestStateStatsMetrics.onNetworkRequestReceived(req);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005441 }
5442 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08005443
Chalard Jeanb5becbc2021-03-05 19:18:14 +09005444 // If this NRI has a satisfier already, it is replacing an older request that
5445 // has been removed. Track it.
5446 final NetworkRequest activeRequest = nri.getActiveRequest();
5447 if (null != activeRequest) {
5448 // If there is an active request, then for sure there is a satisfier.
5449 nri.getSatisfier().addRequest(activeRequest);
5450 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09005451 }
James Mattisf7027322020-12-13 16:28:14 -08005452
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09005453 if (mFlags.noRematchAllRequestsOnRegister()) {
5454 rematchNetworksAndRequests(nris);
5455 } else {
5456 rematchAllNetworksAndRequests();
5457 }
James Mattis45d81842021-01-10 14:24:24 -08005458
Chalard Jean0354d8c2021-01-12 10:58:56 +09005459 // Requests that have not been matched to a network will not have been sent to the
5460 // providers, because the old satisfier and the new satisfier are the same (null in this
5461 // case). Send these requests to the providers.
5462 for (final NetworkRequestInfo nri : nris) {
5463 for (final NetworkOfferInfo noi : mNetworkOffers) {
5464 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08005465 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005466 }
5467 }
5468
James Mattisf7027322020-12-13 16:28:14 -08005469 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
5470 final int callingUid) {
5471 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005472 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08005473 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
5474 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
5475 handleReleaseNetworkRequest(
5476 nri.mRequests.get(0),
5477 callingUid,
5478 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005479 }
5480 }
5481
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005482 // Determines whether the network is the best (or could become the best, if it validated), for
5483 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
5484 // on the value of reason:
5485 //
5486 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
5487 // then it should be torn down.
5488 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
5489 // then it should be lingered.
5490 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005491 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09005492
Chalard Jean254bd162022-08-25 13:04:51 +09005493 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09005494 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
5495 return false;
5496 }
5497
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005498 final int numRequests;
5499 switch (reason) {
5500 case TEARDOWN:
5501 numRequests = nai.numRequestNetworkRequests();
5502 break;
5503 case LINGER:
5504 numRequests = nai.numForegroundNetworkRequests();
5505 break;
5506 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005507 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005508 return true;
5509 }
5510
Chalard Jean947acd42021-03-08 22:29:27 +09005511 if (numRequests > 0) return false;
5512
Paul Jensende49eb12015-06-25 15:30:08 -04005513 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08005514 if (reason == UnneededFor.LINGER
5515 && !nri.isMultilayerRequest()
5516 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09005517 // Background requests don't affect lingering.
5518 continue;
5519 }
5520
James Mattis3d229892020-11-16 16:46:28 -08005521 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04005522 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05005523 }
5524 }
Paul Jensende49eb12015-06-25 15:30:08 -04005525 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05005526 }
5527
James Mattis3d229892020-11-16 16:46:28 -08005528 private boolean isNetworkPotentialSatisfier(
5529 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
Chalard Jean80685f42023-10-30 18:31:27 +09005530 // While destroyed network sometimes satisfy requests (including occasionally newly
5531 // satisfying requests), *potential* satisfiers are networks that might beat a current
5532 // champion if they validate. As such, a destroyed network is never a potential satisfier,
5533 // because it's never a good idea to keep a destroyed network in case it validates.
5534 // For example, declaring it a potential satisfier would keep an unvalidated destroyed
5535 // candidate after it's been replaced by another unvalidated network.
5536 if (candidate.isDestroyed()) return false;
5537 // Listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08005538 // request, return immediately. For multilayer requests, check to see if any of the
5539 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005540 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
5541 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08005542 return false;
5543 }
5544 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08005545 // This multilayer listen request is satisfied therefore no further requests need to be
5546 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08005547 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08005548 return false;
5549 }
James Mattis3d229892020-11-16 16:46:28 -08005550 // As non-multilayer listen requests have already returned, the below would only happen
5551 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08005552 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08005553 continue;
5554 }
Chalard Jean80685f42023-10-30 18:31:27 +09005555 // If there is hope for this network might validate and subsequently become the best
5556 // network for that request, then it is needed. Note that this network can't already
5557 // be the best for this request, or it would be the current satisfier, and therefore
5558 // there would be no need to call this method to find out if it is a *potential*
5559 // satisfier ("unneeded", the only caller, only calls this if this network currently
5560 // satisfies no request).
James Mattis3d229892020-11-16 16:46:28 -08005561 if (candidate.satisfies(req)) {
5562 // As soon as a network is found that satisfies a request, return. Specifically for
5563 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
5564 // is important so as to not evaluate lower priority requests further in
5565 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09005566 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
5567 ? nri.getSatisfier() : null;
5568 // Note that this catches two important cases:
5569 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
5570 // is currently satisfying the request. This is desirable when
5571 // cellular ends up validating but WiFi does not.
5572 // 2. Unvalidated WiFi will not be reaped when validated cellular
5573 // is currently satisfying the request. This is desirable when
5574 // WiFi ends up validating and out scoring cellular.
5575 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08005576 }
5577 }
5578
5579 return false;
5580 }
5581
Erik Kline0c04b742016-07-07 16:50:58 +09005582 private NetworkRequestInfo getNriForAppRequest(
5583 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08005584 // Looking up the app passed param request in mRequests isn't possible since it may return
5585 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
5586 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08005587 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
5588 // to avoid potential race conditions when validating a package->uid mapping when sending
5589 // the callback on the very low-chance that an application shuts down prior to the callback
5590 // being sent.
5591 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
5592 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09005593
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005594 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08005595 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09005596 log(String.format("UID %d attempted to %s for unowned request %s",
5597 callingUid, requestedOperation, nri));
5598 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04005599 }
Erik Kline0c04b742016-07-07 16:50:58 +09005600 }
5601
5602 return nri;
5603 }
5604
James Mattisf7027322020-12-13 16:28:14 -08005605 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
5606 final String callingMethod) {
5607 if (nri.isMultilayerRequest()) {
5608 throw new IllegalStateException(
5609 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09005610 }
5611 }
5612
James Mattisf7027322020-12-13 16:28:14 -08005613 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09005614 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08005615 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
5616 // single NetworkRequest and thus does not apply to multilayer requests.
5617 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
5618 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09005619 return;
5620 }
James Mattis2516da32021-01-31 17:06:19 -08005621 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005622 return;
5623 }
James Mattisf7027322020-12-13 16:28:14 -08005624 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
5625 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09005626 }
5627 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08005628 callCallbackForRequest(
5629 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09005630 }
5631
James Mattisf7027322020-12-13 16:28:14 -08005632 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
5633 final int callingUid,
5634 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005635 final NetworkRequestInfo nri =
5636 getNriForAppRequest(request, callingUid, "release NetworkRequest");
5637 if (nri == null) {
5638 return;
Erik Kline155a59a2015-11-25 12:49:38 +09005639 }
James Mattisf7027322020-12-13 16:28:14 -08005640 if (VDBG || (DBG && request.isRequest())) {
5641 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09005642 }
5643 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08005644 if (callOnUnavailable) {
5645 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
5646 }
Erik Kline155a59a2015-11-25 12:49:38 +09005647 }
Erik Kline0c04b742016-07-07 16:50:58 +09005648
James Mattisa076c532020-12-02 14:12:41 -08005649 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09005650 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08005651 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07005652 if (null == mNetworkRequests.remove(req)) {
5653 logw("Attempted removal of untracked request " + req + " for nri " + nri);
5654 continue;
5655 }
James Mattisa076c532020-12-02 14:12:41 -08005656 if (req.isListen()) {
5657 removeListenRequestFromNetworks(req);
Danuta Brotikovskaya878fd252023-12-28 18:21:21 +00005658 } else if (req.isRequest() && mNetworkRequestStateStatsMetrics != null) {
5659 mNetworkRequestStateStatsMetrics.onNetworkRequestRemoved(req);
James Mattisa076c532020-12-02 14:12:41 -08005660 }
5661 }
James Mattis8f036802021-06-20 16:26:01 -07005662 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09005663 if (mDefaultNetworkRequests.remove(nri)) {
5664 // If this request was one of the defaults, then the UID rules need to be updated
5665 // WARNING : if the app(s) for which this network request is the default are doing
5666 // traffic, this will kill their connected sockets, even if an equivalent request
5667 // is going to be reinstated right away ; unconnected traffic will go on the default
5668 // until the new default is set, which will happen very soon.
5669 // TODO : The only way out of this is to diff old defaults and new defaults, and only
5670 // remove ranges for those requests that won't have a replacement
5671 final NetworkAgentInfo satisfier = nri.getSatisfier();
5672 if (null != satisfier) {
5673 try {
paulhu0e79d952021-06-09 16:11:35 +08005674 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
5675 satisfier.network.getNetId(),
5676 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08005677 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09005678 } catch (RemoteException e) {
5679 loge("Exception setting network preference default network", e);
5680 }
5681 }
5682 }
Junyu Lai35665cc2022-12-19 17:37:48 +08005683
Junyu Lai00d92df2022-07-05 11:01:52 +08005684 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09005685 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09005686 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08005687
5688 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09005689 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08005690 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08005691 }
5692 }
5693
Chalard Jean0354d8c2021-01-12 10:58:56 +09005694 // For all outstanding offers, cancel any of the layers of this NRI that used to be
5695 // needed for this offer.
5696 for (final NetworkOfferInfo noi : mNetworkOffers) {
5697 for (final NetworkRequest req : nri.mRequests) {
5698 if (req.isRequest() && noi.offer.neededFor(req)) {
5699 noi.offer.onNetworkUnneeded(req);
5700 }
5701 }
5702 }
James Mattisa076c532020-12-02 14:12:41 -08005703 }
5704
James Mattis3ce3d3c2021-02-09 18:18:28 -08005705 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
5706 for (final NetworkRequestInfo nri : nris) {
5707 if (mDefaultRequest == nri) {
5708 // Make sure we never remove the default request.
5709 continue;
5710 }
5711 handleRemoveNetworkRequest(nri);
5712 }
5713 }
5714
James Mattisa076c532020-12-02 14:12:41 -08005715 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
5716 // listens don't have a singular affected Network. Check all networks to see
5717 // if this listen request applies and remove it.
5718 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
5719 nai.removeRequest(req.requestId);
5720 if (req.networkCapabilities.hasSignalStrength()
5721 && nai.satisfiesImmutableCapabilitiesOf(req)) {
5722 updateSignalStrengthThresholds(nai, "RELEASE", req);
5723 }
5724 }
5725 }
5726
5727 /**
5728 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
5729 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
5730 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
5731 */
5732 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
5733 boolean wasKept = false;
5734 final NetworkAgentInfo nai = nri.getSatisfier();
5735 if (nai != null) {
5736 final int requestLegacyType = nri.getActiveRequest().legacyType;
5737 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
5738 nai.removeRequest(nri.getActiveRequest().requestId);
5739 if (VDBG || DDBG) {
5740 log(" Removing from current network " + nai.toShortString()
5741 + ", leaving " + nai.numNetworkRequests() + " requests.");
5742 }
5743 // If there are still lingered requests on this network, don't tear it down,
5744 // but resume lingering instead.
5745 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08005746 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08005747 notifyNetworkLosing(nai, now);
5748 }
5749 if (unneeded(nai, UnneededFor.TEARDOWN)) {
5750 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
5751 teardownUnneededNetwork(nai);
5752 } else {
5753 wasKept = true;
5754 }
James Mattisa076c532020-12-02 14:12:41 -08005755 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
5756 // Went from foreground to background.
5757 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09005758 }
5759
Erik Kline0c04b742016-07-07 16:50:58 +09005760 // Maintain the illusion. When this request arrived, we might have pretended
5761 // that a network connected to serve it, even though the network was already
5762 // connected. Now that this request has gone away, we might have to pretend
5763 // that the network disconnected. LegacyTypeTracker will generate that
5764 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005765 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005766 boolean doRemove = true;
5767 if (wasKept) {
5768 // check if any of the remaining requests for this network are for the
5769 // same legacy type - if so, don't remove the nai
5770 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5771 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005772 if (otherRequest.legacyType == requestLegacyType
5773 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005774 if (DBG) log(" still have other legacy request - leaving");
5775 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005776 }
5777 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005778 }
5779
Erik Kline0c04b742016-07-07 16:50:58 +09005780 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005781 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005782 }
5783 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005784 }
5785 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005786
Junyu Lai00d92df2022-07-05 11:01:52 +08005787 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai71b51532024-02-01 10:39:01 +08005788 return hasAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005789 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5790 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5791 }
5792
Lorenzo Colittid6459092016-07-04 12:55:44 +09005793 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005794 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005795 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005796 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005797 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005798 }
5799
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005800 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005801 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5802 enforceNetworkStackSettingsOrSetup();
5803 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5804 encodeBool(accept), encodeBool(always), network));
5805 }
5806
5807 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005808 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005809 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005810 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5811 }
5812
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005813 @Override
5814 public void setTestAllowBadWifiUntil(long timeMs) {
5815 enforceSettingsPermission();
5816 if (!Build.isDebuggable()) {
5817 throw new IllegalStateException("Does not support in non-debuggable build");
5818 }
5819
5820 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5821 throw new IllegalArgumentException("It should not exceed "
5822 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5823 }
5824
5825 mHandler.sendMessage(
5826 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5827 }
5828
chiachangwange0192a72023-02-06 13:25:01 +00005829 @Override
5830 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5831 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005832
5833 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5834 throw new IllegalArgumentException("Argument should not exceed "
5835 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5836 }
5837
5838 mHandler.sendMessage(
5839 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5840 }
5841
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005842 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5843 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5844 " accept=" + accept + " always=" + always);
5845
5846 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5847 if (nai == null) {
5848 // Nothing to do.
5849 return;
5850 }
5851
Chalard Jean254bd162022-08-25 13:04:51 +09005852 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005853 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005854 return;
5855 }
5856
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005857 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005858 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005859 }
5860
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005861 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5862 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005863 // If network becomes partial connectivity and user already accepted to use this
5864 // network, we should respect the user's option and don't need to popup the
5865 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005866 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005867 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005868 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005869 }
5870
5871 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005872 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005873 }
5874
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005875 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005876 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005877 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005878 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005879 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005880 }
5881
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005882 }
5883
lucaslin2240ef62019-03-12 13:08:03 +08005884 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5885 boolean always) {
5886 if (DBG) {
5887 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5888 + " always=" + always);
5889 }
5890
5891 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5892 if (nai == null) {
5893 // Nothing to do.
5894 return;
5895 }
5896
Chalard Jean254bd162022-08-25 13:04:51 +09005897 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005898 // The network validated while the dialog box was up. Take no action.
5899 return;
5900 }
5901
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005902 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5903 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005904 }
5905
5906 // TODO: Use the current design or save the user choice into IpMemoryStore.
5907 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005908 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005909 }
5910
5911 if (!accept) {
5912 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005913 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005914 // Tear down the network.
5915 teardownUnneededNetwork(nai);
5916 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005917 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5918 // result in a partial connectivity result which will be processed by
5919 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005920 //
5921 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5922 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005923 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005924 }
5925 }
5926
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005927 private void handleSetAvoidUnvalidated(Network network) {
5928 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005929 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005930 // Nothing to do. The network either disconnected or revalidated.
5931 return;
5932 }
Chalard Jean254bd162022-08-25 13:04:51 +09005933 if (0L == nai.getAvoidUnvalidated()) {
5934 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005935 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005936 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005937 }
5938 }
5939
Chalard Jean5fb43c72022-09-08 19:03:14 +09005940 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005941 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005942 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Chalard Jean6f6c3532023-05-15 17:26:13 +09005943 mDeps.scheduleEvaluationTimeout(mHandler, network, delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005944 }
5945
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005946 @Override
5947 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005948 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005949 mHandler.post(() -> {
5950 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5951 if (nai == null) return;
5952 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005953 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005954 });
5955 }
5956
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005957 /**
5958 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5959 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005960 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005961 * @param appExtras Bundle to use as intent extras for the captive portal application.
5962 * Must be treated as opaque to avoid preventing the captive portal app to
5963 * update its arguments.
5964 */
5965 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005966 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005967 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5968 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005969
5970 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5971 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005972 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5973 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005974 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5975
lucaslin75ff7022020-12-17 04:14:35 +08005976 final long token = Binder.clearCallingIdentity();
5977 try {
5978 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5979 } finally {
5980 Binder.restoreCallingIdentity(token);
5981 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005982 }
5983
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005984 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5985 private final Network mNetwork;
5986
5987 private CaptivePortalImpl(Network network) {
5988 mNetwork = network;
5989 }
5990
5991 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005992 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005993 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5994 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005995 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5996 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5997 // Since the network will be disconnected, skip notifying NetworkMonitor
5998 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005999 }
6000
Chiachang Wang938bfba2020-01-09 13:50:55 +08006001 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006002 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006003 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006004 }
6005
6006 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08006007 public void appRequest(final int request) {
6008 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
6009 if (nm == null) return;
6010
6011 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Junyu Lai71b51532024-02-01 10:39:01 +08006012 hasNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006013 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08006014 }
6015 }
6016
6017 @Nullable
6018 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
6019 // getNetworkAgentInfoForNetwork is thread-safe
6020 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6021 if (nai == null) return null;
6022
6023 // nai.networkMonitor() is thread-safe
6024 return nai.networkMonitor();
6025 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09006026 }
6027
Hugo Benichic9048bc2016-09-14 23:23:08 +00006028 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006029 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09006030 }
6031
Chalard Jean020b93a2022-09-01 13:20:14 +09006032 private boolean activelyPreferBadWifi() {
6033 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
6034 }
6035
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09006036 /**
6037 * Return whether the device should maintain continuous, working connectivity by switching away
6038 * from WiFi networks having no connectivity.
6039 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
6040 */
6041 public boolean shouldAvoidBadWifi() {
Junyu Lai71b51532024-02-01 10:39:01 +08006042 if (!hasNetworkStackPermission()) {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09006043 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
6044 }
6045 return avoidBadWifi();
6046 }
6047
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006048 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09006049 ensureRunningOnConnectivityServiceThread();
6050 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09006051 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006052 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09006053 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09006054 if (avoidBadWifi) {
6055 // If the device is now avoiding bad wifi, remove notifications that might have
6056 // been put up when the device didn't.
6057 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
6058 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09006059 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09006060 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
6061 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
6062 for (final NetworkOfferInfo noi : offersToUpdate) {
6063 updateOfferScore(noi.offer);
6064 }
Chalard Jean020b93a2022-09-01 13:20:14 +09006065 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09006066 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006067 }
6068
Erik Kline95ecfee2016-10-02 18:02:14 +09006069 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006070 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006071 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09006072 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006073 if (!configRestrict) {
6074 pw.println("Bad Wi-Fi avoidance: unrestricted");
6075 return;
6076 }
6077
6078 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
6079 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09006080 pw.println("Config restrict: " + configRestrict);
6081 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006082
Chalard Jeane0fdea32022-09-14 21:44:22 +09006083 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006084 String description;
6085 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09006086 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006087 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006088 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006089 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09006090 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006091 description = "avoid";
6092 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09006093 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006094 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09006095 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00006096
6097 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
6098 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09006099 if (null == configValue) {
6100 description = "unset";
6101 } else if (configValue) {
6102 description = "force true";
6103 } else {
6104 description = "force false";
6105 }
6106 pw.println("Actively prefer bad wifi conf: " + description);
6107 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006108 pw.println("Network overrides:");
6109 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09006110 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09006111 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09006112 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09006113 }
6114 }
6115 pw.decreaseIndent();
6116 pw.decreaseIndent();
6117 }
6118
paulhu7746e4e2020-06-09 19:07:03 +08006119 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
6120 // unify the method.
6121 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
6122 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
6123 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
6124 return settingsComponent != null
6125 ? settingsComponent.getPackageName() : "com.android.settings";
6126 }
6127
lucaslinb1e8e382019-01-24 15:55:30 +08006128 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006129 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006130 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006131 switch (type) {
6132 case NO_INTERNET:
6133 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006134 // High priority because it is only displayed for explicitly selected networks.
6135 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006136 break;
lucasline117e2e2019-10-22 18:27:33 +08006137 case PRIVATE_DNS_BROKEN:
6138 action = Settings.ACTION_WIRELESS_SETTINGS;
6139 // High priority because we should let user know why there is no internet.
6140 highPriority = true;
6141 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006142 case LOST_INTERNET:
6143 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006144 // High priority because it could help the user avoid unexpected data usage.
6145 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006146 break;
lucaslin2240ef62019-03-12 13:08:03 +08006147 case PARTIAL_CONNECTIVITY:
6148 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006149 // Don't bother the user with a high-priority notification if the network was not
6150 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006151 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08006152 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006153 default:
Aaron Huang6616df32020-10-30 22:04:25 +08006154 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006155 return;
6156 }
6157
6158 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08006159 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08006160 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08006161 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08006162 // Some OEMs have their own Settings package. Thus, need to get the current using
6163 // Settings package name instead of just use default name "com.android.settings".
6164 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
6165 intent.setClassName(settingsPkgName,
6166 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08006167 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006168
paulhu2af50222020-10-11 22:52:27 +08006169 PendingIntent pendingIntent = PendingIntent.getActivity(
6170 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08006171 0 /* requestCode */,
6172 intent,
paulhu2af50222020-10-11 22:52:27 +08006173 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09006174
Serik Beketayevec8ad212020-12-07 22:43:07 -08006175 mNotifier.showNotification(
6176 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006177 }
6178
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006179 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
6180 // Don't prompt if the network is validated, and don't prompt on captive portals
6181 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09006182 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006183 return false;
6184 }
6185
6186 // If a network has partial connectivity, always prompt unless the user has already accepted
6187 // partial connectivity and selected don't ask again. This ensures that if the device
6188 // automatically connects to a network that has partial Internet access, the user will
6189 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09006190 // because we have prompted them.
6191 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006192 return true;
6193 }
6194
6195 // If a network has no Internet access, only prompt if the network was explicitly selected
6196 // and if the user has not already told us to use the network regardless of whether it
6197 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09006198 if (nai.networkAgentConfig.explicitlySelected
6199 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09006200 return true;
6201 }
6202
6203 return false;
6204 }
6205
Chalard Jean5fb43c72022-09-08 19:03:14 +09006206 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
6207 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006208
Chalard Jean5fb43c72022-09-08 19:03:14 +09006209 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6210 if (null == nai) return;
6211
6212 if (nai.setEvaluated()) {
6213 // If setEvaluated() returned true, the network never had any form of connectivity.
6214 // This may have an impact on request matching if bad WiFi avoidance is off and the
6215 // network was found not to have Internet access.
6216 nai.updateScoreForNetworkAgentUpdate();
6217 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09006218
6219 // Also, if this is WiFi and it should be preferred actively, now is the time to
6220 // prompt the user that they walked past and connected to a bad WiFi.
6221 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
6222 && !avoidBadWifi()
6223 && activelyPreferBadWifi()) {
6224 // The notification will be removed if the network validates or disconnects.
6225 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
6226 return;
6227 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006228 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006229
Chalard Jean5fb43c72022-09-08 19:03:14 +09006230 if (!shouldPromptUnvalidated(nai)) return;
6231
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006232 // Stop automatically reconnecting to this network in the future. Automatically connecting
6233 // to a network that provides no or limited connectivity is not useful, because the user
6234 // cannot use that network except through the notification shown by this method, and the
6235 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006236 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09006237
Chalard Jean254bd162022-08-25 13:04:51 +09006238 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08006239 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08006240 } else {
6241 showNetworkNotification(nai, NotificationType.NO_INTERNET);
6242 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006243 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006244
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006245 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
6246 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09006247 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07006248
lucaslin2240ef62019-03-12 13:08:03 +08006249 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
6250 return;
6251 }
6252
6253 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08006254 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09006255 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006256 }
6257
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006258 @Override
6259 public int getMultipathPreference(Network network) {
6260 enforceAccessPermission();
6261
6262 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06006263 if (nai != null && nai.networkCapabilities
6264 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006265 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
6266 }
6267
Aaron Huang9a57acf2020-12-08 10:03:29 +08006268 final NetworkPolicyManager netPolicyManager =
6269 mContext.getSystemService(NetworkPolicyManager.class);
6270
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09006271 final long token = Binder.clearCallingIdentity();
6272 final int networkPreference;
6273 try {
6274 networkPreference = netPolicyManager.getMultipathPreference(network);
6275 } finally {
6276 Binder.restoreCallingIdentity(token);
6277 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08006278 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09006279 return networkPreference;
6280 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09006281 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
6282 }
6283
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006284 @Override
6285 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09006286 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006287 }
6288
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006289 private class InternalHandler extends Handler {
6290 public InternalHandler(Looper looper) {
6291 super(looper);
6292 }
6293
6294 @Override
6295 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07006296 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07006297 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006298 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006299 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07006300 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006301 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07006302 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09006303 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07006304 break;
6305 }
Aaron Huang9fe47be2021-06-08 13:11:45 +08006306 case EVENT_PAC_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08006307 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
Aaron Huang9fe47be2021-06-08 13:11:45 +08006308 handlePacProxyServiceStarted(arg.first, arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04006309 break;
6310 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006311 case EVENT_REGISTER_NETWORK_PROVIDER: {
6312 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006313 break;
6314 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006315 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
6316 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006317 break;
6318 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09006319 case EVENT_REGISTER_NETWORK_OFFER: {
6320 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
6321 break;
6322 }
6323 case EVENT_UNREGISTER_NETWORK_OFFER: {
6324 final NetworkOfferInfo offer =
6325 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
6326 if (null != offer) {
6327 handleUnregisterNetworkOffer(offer);
6328 }
6329 break;
6330 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006331 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09006332 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
6333 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
6334 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07006335 break;
6336 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006337 case EVENT_REGISTER_NETWORK_REQUEST:
6338 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09006339 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006340 break;
6341 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04006342 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
6343 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006344 handleRegisterNetworkRequestWithIntent(msg);
6345 break;
6346 }
Erik Kline155a59a2015-11-25 12:49:38 +09006347 case EVENT_TIMEOUT_NETWORK_REQUEST: {
6348 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
6349 handleTimedOutNetworkRequest(nri);
6350 break;
6351 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006352 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
6353 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
6354 break;
6355 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006356 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08006357 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
6358 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006359 break;
6360 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006361 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09006362 Network network = (Network) msg.obj;
6363 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006364 break;
6365 }
lucaslin2240ef62019-03-12 13:08:03 +08006366 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
6367 Network network = (Network) msg.obj;
6368 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
6369 toBool(msg.arg2));
6370 break;
6371 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09006372 case EVENT_SET_AVOID_UNVALIDATED: {
6373 handleSetAvoidUnvalidated((Network) msg.obj);
6374 break;
6375 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09006376 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
6377 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09006378 break;
6379 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07006380 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
6381 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09006382 break;
6383 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006384 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
6385 // handler thread.
6386 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006387 mKeepaliveTracker.handleStartKeepalive(msg);
6388 break;
6389 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00006390 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09006391 final AutomaticOnOffKeepalive ki =
6392 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
6393 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006394
chiachangwang676c84e2023-02-14 09:22:05 +00006395 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006396 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006397 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00006398 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006399 for (NetworkAgentInfo n : mNetworkAgentInfos) {
6400 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00006401 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
6402 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006403 }
6404 }
6405
6406 // If the network no longer exists, then the keepalive should have been
6407 // cleaned up already. There is no point trying to resume keepalives.
6408 if (!networkFound) return;
6409
chiachangwang676c84e2023-02-14 09:22:05 +00006410 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006411 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
Chiachang Wangac2e8f32024-01-18 12:55:11 +00006412 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006413 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00006414 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09006415 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00006416 }
6417 break;
6418 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006419 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08006420 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006421 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
6422 (IBinder) msg.obj);
6423 if (ki == null) {
6424 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00006425 return;
6426 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09006427 final int reason = msg.arg2;
6428 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09006429 break;
6430 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006431 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
6432 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
6433 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006434 break;
6435 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09006436 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
6437 handlePrivateDnsSettingsChanged();
6438 break;
dalyk1720e542018-03-05 12:42:22 -05006439 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
6440 handlePrivateDnsValidationUpdate(
6441 (PrivateDnsValidationUpdate) msg.obj);
6442 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00006443 case EVENT_UID_BLOCKED_REASON_CHANGED:
6444 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08006445 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006446 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
6447 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
6448 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006449 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09006450 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
6451 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006452 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08006453 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006454 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006455 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09006456 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
6457 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006458 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08006459 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09006460 }
lucaslin1193a5d2021-01-21 02:04:15 +08006461 case EVENT_REPORT_NETWORK_ACTIVITY:
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +09006462 final NetworkActivityParams arg = (NetworkActivityParams) msg.obj;
Motomu Utsumi188bfd32023-05-30 14:38:04 +09006463 handleReportNetworkActivity(arg);
lucaslin1193a5d2021-01-21 02:04:15 +08006464 break;
paulhu51f77dc2021-06-07 02:34:20 +00006465 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
6466 handleMobileDataPreferredUidsChanged();
6467 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08006468 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
6469 final long timeMs = ((Long) msg.obj).longValue();
6470 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
6471 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01006472 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
6473 handleIngressRateLimitChanged();
6474 break;
Hansen Kurli55396972022-10-28 03:31:17 +00006475 case EVENT_USER_DOES_NOT_WANT:
6476 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
6477 if (nai == null) break;
6478 nai.onPreventAutomaticReconnect();
Jean Chalard3160bc02023-06-27 08:54:23 +00006479 nai.disconnect();
Hansen Kurli55396972022-10-28 03:31:17 +00006480 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00006481 case EVENT_SET_VPN_NETWORK_PREFERENCE:
6482 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
6483 break;
chiachangwange0192a72023-02-06 13:25:01 +00006484 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
6485 final long time = ((Long) msg.obj).longValue();
6486 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
6487 break;
6488 }
Mark Fasheh7c999d82023-05-04 20:23:11 +00006489 case EVENT_UID_FROZEN_STATE_CHANGED:
6490 UidFrozenStateChangedArgs args = (UidFrozenStateChangedArgs) msg.obj;
6491 handleFrozenUids(args.mUids, args.mFrozenStates);
6492 break;
Ying Xu7cabd322024-01-15 18:40:15 -08006493 case EVENT_UID_CARRIER_PRIVILEGES_LOST:
6494 handleUidCarrierPrivilegesLost(msg.arg1);
6495 break;
The Android Open Source Project28527d22009-03-03 19:31:44 -08006496 }
6497 }
6498 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006499
Lorenzo Colittid6459092016-07-04 12:55:44 +09006500 @Override
markchien5776f962019-12-16 20:15:20 +08006501 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006502 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08006503 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006504 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6505 Context.TETHERING_SERVICE);
6506 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006507 }
6508
Lorenzo Colittid6459092016-07-04 12:55:44 +09006509 @Override
markchien5776f962019-12-16 20:15:20 +08006510 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006511 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08006512 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006513 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6514 Context.TETHERING_SERVICE);
6515 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006516 }
6517
Lorenzo Colittid6459092016-07-04 12:55:44 +09006518 @Override
markchien5776f962019-12-16 20:15:20 +08006519 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006520 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006521 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006522 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6523 Context.TETHERING_SERVICE);
6524 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08006525 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08006526
markchien5776f962019-12-16 20:15:20 +08006527
Lorenzo Colittid6459092016-07-04 12:55:44 +09006528 @Override
markchien5776f962019-12-16 20:15:20 +08006529 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006530 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08006531 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006532 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6533 Context.TETHERING_SERVICE);
6534
6535 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08006536 }
6537
Lorenzo Colittid6459092016-07-04 12:55:44 +09006538 @Override
markchien5776f962019-12-16 20:15:20 +08006539 @Deprecated
6540 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08006541 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006542 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6543 Context.TETHERING_SERVICE);
6544
6545 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07006546 }
6547
Udam Saini8f7d6a72017-06-07 12:06:28 -07006548 @Override
markchien5776f962019-12-16 20:15:20 +08006549 @Deprecated
6550 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08006551 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08006552 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
6553 Context.TETHERING_SERVICE);
6554 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08006555 }
6556
Robert Greenwalte0b00512014-07-02 09:59:16 -07006557 // Called when we lose the default network and have no replacement yet.
6558 // This will automatically be cleared after X seconds or a new default network
6559 // becomes CONNECTED, whichever happens first. The timer is started by the
6560 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09006561 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006562 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006563 if (mNetTransitionWakeLock.isHeld()) {
6564 return;
6565 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006566 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006567 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
6568 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006569 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006570 mWakelockLogs.log("ACQUIRE for " + forWhom);
6571 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006572 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09006573 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09006574 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07006575 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07006576
Hugo Benichi471b62a2017-03-30 23:18:10 +09006577 // Called when we gain a new default network to release the network transition wakelock in a
6578 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
6579 // message is cancelled.
6580 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09006581 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09006582 if (!mNetTransitionWakeLock.isHeld()) {
6583 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09006584 }
6585 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006586 // Cancel self timeout on wakelock hold.
6587 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
6588 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
6589 mHandler.sendMessageDelayed(msg, 1000);
6590 }
6591
6592 // Called when either message of ensureNetworkTransitionWakelock or
6593 // scheduleReleaseNetworkTransitionWakelock is processed.
6594 private void handleReleaseNetworkTransitionWakelock(int eventId) {
6595 String event = eventName(eventId);
6596 synchronized (this) {
6597 if (!mNetTransitionWakeLock.isHeld()) {
6598 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08006599 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09006600 return;
6601 }
6602 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09006603 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
6604 mTotalWakelockDurationMs += lockDuration;
6605 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
6606 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09006607 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09006608 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09006609 }
6610
Robert Greenwalt986c7412010-09-08 15:24:47 -07006611 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09006612 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07006613 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07006614 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09006615 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04006616 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07006617 }
6618
Lorenzo Colittid6459092016-07-04 12:55:44 +09006619 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04006620 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04006621 enforceAccessPermission();
6622 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006623 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09006624 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006625
6626 final NetworkAgentInfo nai;
6627 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09006628 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08006629 } else {
6630 nai = getNetworkAgentInfoForNetwork(network);
6631 }
Cody Kesting3d1df812020-06-25 11:13:39 -07006632
6633 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07006634 mHandler.obtainMessage(
6635 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09006636 }
Paul Jensen83f5d572014-08-29 09:54:01 -04006637
Hugo Benichid6b510a2017-04-06 17:22:18 +09006638 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07006639 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006640 if (nai == null
6641 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07006642 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04006643 return;
6644 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006645 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09006646 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07006647 mConnectivityDiagnosticsHandler.sendMessage(
6648 mConnectivityDiagnosticsHandler.obtainMessage(
6649 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6650 new ReportedNetworkConnectivityInfo(
6651 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09006652 return;
6653 }
Paul Jensenb95d7952015-04-07 12:43:13 -04006654 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08006655 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09006656 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04006657 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09006658 // Validating a network that has not yet connected could result in a call to
6659 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09006660 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006661 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04006662 }
paulhu7aeba372020-12-30 00:42:19 +08006663 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
6664 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09006665 return;
6666 }
Cody Kestingf1120be2020-08-03 18:01:40 -07006667
6668 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
6669 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
6670 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
6671 // completed.
6672 mConnectivityDiagnosticsHandler.sendMessage(
6673 mConnectivityDiagnosticsHandler.obtainMessage(
6674 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
6675 new ReportedNetworkConnectivityInfo(
6676 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09006677 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006678 }
6679
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006680 // TODO: call into netd.
6681 private boolean queryUserAccess(int uid, Network network) {
6682 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6683 if (nai == null) return false;
6684
6685 // Any UID can use its default network.
6686 if (nai == getDefaultNetworkForUid(uid)) return true;
6687
6688 // Privileged apps can use any network.
6689 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
6690 return true;
6691 }
6692
6693 // An unprivileged UID can use a VPN iff the VPN applies to it.
6694 if (nai.isVPN()) {
6695 return nai.networkCapabilities.appliesToUid(uid);
6696 }
6697
6698 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
6699 // sockets, i.e., if it is the owner.
6700 final NetworkAgentInfo vpn = getVpnForUid(uid);
6701 if (vpn != null && !vpn.networkAgentConfig.allowBypass
6702 && uid != vpn.networkCapabilities.getOwnerUid()) {
6703 return false;
6704 }
6705
6706 // The UID's permission must be at least sufficient for the network. Since the restricted
6707 // permission was already checked above, that just leaves background networks.
6708 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
6709 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
6710 }
6711
6712 // Unrestricted network. Anyone gets to use it.
6713 return true;
6714 }
6715
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006716 /**
6717 * Returns information about the proxy a certain network is using. If given a null network, it
6718 * it will return the proxy for the bound network for the caller app or the default proxy if
6719 * none.
6720 *
6721 * @param network the network we want to get the proxy information for.
6722 * @return Proxy information if a network has a proxy configured, or otherwise null.
6723 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09006724 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04006725 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09006726 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04006727 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006728 if (network == null) {
6729 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006730 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006731 true);
6732 if (activeNetwork == null) {
6733 return null;
6734 }
6735 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09006736 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006737 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
6738 // caller may not have.
6739 return getLinkPropertiesProxyInfo(network);
6740 }
6741 // No proxy info available if the calling UID does not have network access.
6742 return null;
6743 }
6744
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006745
6746 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04006747 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
6748 if (nai == null) return null;
6749 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006750 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
6751 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04006752 }
6753 }
6754
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006755 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09006756 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08006757 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09006758 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006759 }
6760
Chalard Jean777e2e52018-06-07 18:02:37 +09006761 @Override
6762 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04006763 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09006764 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006765 }
6766
Aaron Huang9fe47be2021-06-08 13:11:45 +08006767 private void handlePacProxyServiceStarted(@Nullable Network net, @Nullable ProxyInfo proxy) {
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006768 mProxyTracker.setDefaultProxy(proxy);
Aaron Huang9fe47be2021-06-08 13:11:45 +08006769 final NetworkAgentInfo nai = getDefaultNetwork();
6770 // TODO : this method should check that net == nai.network, unfortunately at this point
6771 // 'net' is always null in practice (see PacProxyService#sendPacBroadcast). PAC proxy
6772 // is only ever installed on the default network so in practice this is okay.
6773 if (null == nai) return;
6774 // PAC proxies only work on the default network. Therefore, only the default network
6775 // should have its link properties fixed up for PAC proxies.
6776 mProxyTracker.updateDefaultNetworkProxyPortForPAC(nai.linkProperties, nai.network);
6777 if (nai.everConnected()) {
6778 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_IP_CHANGED);
6779 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006780 }
6781
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006782 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6783 // when any network changes proxy.
6784 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6785 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006786 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6787 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006788 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6789
Chalard Jean7d97afc2018-06-07 17:41:29 +09006790 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006791 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006792 }
6793 }
6794
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006795 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006796 final private HashMap<Uri, Integer> mUriEventMap;
6797 final private Context mContext;
6798 final private Handler mHandler;
6799
6800 SettingsObserver(Context context, Handler handler) {
6801 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006802 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006803 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006804 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006805 }
6806
Erik Kline05f2b402015-04-30 12:58:40 +09006807 void observe(Uri uri, int what) {
6808 mUriEventMap.put(uri, what);
6809 final ContentResolver resolver = mContext.getContentResolver();
6810 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006811 }
6812
6813 @Override
6814 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006815 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006816 }
6817
6818 @Override
6819 public void onChange(boolean selfChange, Uri uri) {
6820 final Integer what = mUriEventMap.get(uri);
6821 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006822 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006823 } else {
6824 loge("No matching event to send for URI=" + uri);
6825 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006826 }
6827 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006828
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006829 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006830 Log.d(TAG, s);
6831 }
6832
6833 private static void logw(String s) {
6834 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006835 }
6836
Daniel Brightf9e945b2020-06-15 16:10:01 -07006837 private static void logwtf(String s) {
6838 Log.wtf(TAG, s);
6839 }
6840
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006841 private static void logwtf(String s, Throwable t) {
6842 Log.wtf(TAG, s, t);
6843 }
6844
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006845 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006846 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006847 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006848
Hugo Benichi39621362017-02-11 17:04:43 +09006849 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006850 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006851 }
6852
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006853 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006854 * Return the information of all ongoing VPNs.
6855 *
6856 * <p>This method is used to update NetworkStatsService.
6857 *
6858 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006859 */
junyulai2050bed2021-01-23 09:46:34 +08006860 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006861 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006862 if (mLockdownEnabled) {
6863 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006864 }
junyulai2050bed2021-01-23 09:46:34 +08006865 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006866 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006867 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006868 if (info != null) {
6869 infoList.add(info);
6870 }
6871 }
junyulai2050bed2021-01-23 09:46:34 +08006872 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006873 }
6874
6875 /**
6876 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006877 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006878 */
junyulai2050bed2021-01-23 09:46:34 +08006879 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006880 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006881 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6882 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006883 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6884 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6885 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006886 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6887 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006888 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006889 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006890 }
6891 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006892
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006893 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006894
6895 List<String> interfaces = new ArrayList<>();
6896 for (Network network : underlyingNetworks) {
6897 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6898 if (underlyingNai == null) continue;
6899 LinkProperties lp = underlyingNai.linkProperties;
6900 for (String iface : lp.getAllInterfaceNames()) {
6901 if (!TextUtils.isEmpty(iface)) {
6902 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006903 }
6904 }
Benedict Wong34857f82019-06-12 17:46:15 +00006905 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006906
6907 if (interfaces.isEmpty()) return null;
6908
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006909 // Must be non-null or NetworkStatsService will crash.
6910 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6911 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006912 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006913 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006914
junyulai2050bed2021-01-23 09:46:34 +08006915 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6916 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006917 }
6918
James Mattisd31bdfa2020-12-23 16:37:26 -08006919 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006920 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6921 Network[] underlyingNetworks) {
6922 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006923 if (underlyingNetworks == null && defaultNetwork != null) {
6924 // null underlying networks means to track the default.
6925 underlyingNetworks = new Network[] { defaultNetwork };
6926 }
6927 return underlyingNetworks;
6928 }
6929
6930 // Returns true iff |network| is an underlying network of |nai|.
6931 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6932 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6933 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006934 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006935 final Network[] underlying = underlyingNetworksOrDefault(
6936 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006937 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006938 }
6939
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006940 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006941 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006942 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006943 * When underlying networks change, such networks may have to update capabilities to reflect
6944 * things like the metered bit, their transports, and so on. The capabilities are calculated
6945 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006946 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006947 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006948 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006949 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006950 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006951 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006952 }
6953 }
6954 }
6955
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006956 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6957 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6958 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6959 // a VPN is not up.
6960 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6961 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6962 for (UidRange range : blockedUidRanges) {
6963 if (range.contains(uid)) return true;
6964 }
6965 return false;
6966 }
6967
6968 @Override
6969 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006970 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006971 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6972 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6973 }
6974
6975 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6976 if (DBG) {
6977 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6978 + Arrays.toString(ranges));
6979 }
6980 // Cannot use a Set since the list of UID ranges might contain duplicates.
6981 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6982 for (int i = 0; i < ranges.length; i++) {
6983 if (requireVpn) {
6984 newVpnBlockedUidRanges.add(ranges[i]);
6985 } else {
6986 newVpnBlockedUidRanges.remove(ranges[i]);
6987 }
6988 }
6989
6990 try {
6991 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6992 } catch (RemoteException | ServiceSpecificException e) {
6993 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6994 + Arrays.toString(ranges) + "): netd command failed: " + e);
6995 }
6996
Chalard Jeandf29a852023-05-29 17:02:43 +09006997 if (mDeps.isAtLeastT()) {
Motomu Utsumib08654c2022-05-11 05:56:26 +00006998 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6999 }
7000
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007001 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
7002 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00007003 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
7004 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007005 }
7006
7007 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
7008 }
7009
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07007010 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007011 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08007012 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007013 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01007014 }
7015
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007016 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
7017 return mLockdownEnabled
7018 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
7019 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00007020 }
7021
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007022 private NetworkAgentInfo getLegacyLockdownNai() {
7023 if (!mLockdownEnabled) {
7024 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00007025 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007026 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007027 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
7028 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00007029
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007030 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007031 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
7032 // a local variable. There is no need to make a copy because its contents cannot change.
7033 final Network[] underlying = nai.declaredUnderlyingNetworks;
7034 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007035 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007036 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007037
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007038 // The legacy lockdown VPN always uses the default network.
7039 // If the VPN's underlying network is no longer the current default network, it means that
7040 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007041 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
7042 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007043 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09007044 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007045 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007046 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007047
7048 return nai;
7049 };
7050
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007051 // TODO: move all callers to filterForLegacyLockdown and delete this method.
7052 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
7053 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09007054 private DetailedState getLegacyLockdownState(DetailedState origState) {
7055 if (origState != DetailedState.CONNECTED) {
7056 return origState;
7057 }
7058 return (mLockdownEnabled && getLegacyLockdownNai() == null)
7059 ? DetailedState.CONNECTING
7060 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007061 }
7062
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09007063 private void filterForLegacyLockdown(NetworkInfo ni) {
7064 if (!mLockdownEnabled || !ni.isConnected()) return;
7065 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
7066 // state of its VPN. This is to ensure that when an underlying network connects, apps will
7067 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
7068 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
7069 // network, this time with a state of CONNECTED.
7070 //
7071 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
7072 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
7073 // is not too far off the truth, since an always-on VPN, when not connected, is always
7074 // trying to reconnect.
7075 if (getLegacyLockdownNai() == null) {
7076 ni.setDetailedState(DetailedState.CONNECTING, "", null);
7077 }
7078 }
7079
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00007080 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07007081 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04007082 String action) {
paulhu8e96a752019-08-12 16:25:11 +08007083 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09007084 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
7085 return;
7086 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04007087 final long ident = Binder.clearCallingIdentity();
7088 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09007089 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007090 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09007091 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04007092 } finally {
7093 Binder.restoreCallingIdentity(ident);
7094 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07007095 }
Wink Savillecb117d32013-08-29 14:57:08 -07007096
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007097 @Override
7098 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01007099 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007100 final long ident = Binder.clearCallingIdentity();
7101 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007102 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09007103 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07007104 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
7105 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08007106 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07007107 } finally {
7108 Binder.restoreCallingIdentity(ident);
7109 }
7110 }
7111
James Mattis02220e22021-03-13 19:27:21 -08007112 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08007113 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7114 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7115 }
Chalard Jeane0abd522023-01-23 16:47:43 +09007116 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007117 }
7118
James Mattis02220e22021-03-13 19:27:21 -08007119 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09007120 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08007121 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08007122 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
7123 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09007124 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08007125 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
7126 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7127 }
junyulaid91e7052020-08-28 13:44:33 +08007128 }
7129
James Mattis02220e22021-03-13 19:27:21 -08007130 private void onPackageChanged(@NonNull final String packageName) {
7131 // This is necessary in case a package is added or removed, but also when it's replaced to
7132 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
7133 // as one in the preferences, then it should follow the same routing as that other package,
7134 // which means updating the rules is never to be needed in this case (whether it joins or
7135 // leaves a UID with a preference).
7136 if (isMappedInOemNetworkPreference(packageName)) {
7137 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
7138 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007139
7140 // Invalidates cache entry when the package is updated.
7141 synchronized (mSelfCertifiedCapabilityCache) {
7142 mSelfCertifiedCapabilityCache.remove(packageName);
7143 }
James Mattis02220e22021-03-13 19:27:21 -08007144 }
7145
7146 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007147 @Override
7148 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09007149 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007150 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007151 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08007152
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007153 // User should be filled for below intents, check the existence.
7154 if (user == null) {
7155 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
7156 return;
7157 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007158
Lorenzo Colitticd675292021-02-04 17:32:07 +09007159 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007160 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07007161 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09007162 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09007163 } else {
junyulaid91e7052020-08-28 13:44:33 +08007164 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07007165 }
7166 }
7167 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07007168
James Mattis02220e22021-03-13 19:27:21 -08007169 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
7170 @Override
7171 public void onReceive(Context context, Intent intent) {
7172 ensureRunningOnConnectivityServiceThread();
7173 switch (intent.getAction()) {
7174 case Intent.ACTION_PACKAGE_ADDED:
7175 case Intent.ACTION_PACKAGE_REMOVED:
7176 case Intent.ACTION_PACKAGE_REPLACED:
7177 onPackageChanged(intent.getData().getSchemeSpecificPart());
7178 break;
7179 default:
7180 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7181 }
7182 }
7183 };
7184
Junyu Lai38c75032023-12-04 07:52:19 +00007185 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
7186 private final BroadcastReceiver mDataSaverReceiver = new BroadcastReceiver() {
7187 @Override
7188 public void onReceive(Context context, Intent intent) {
7189 if (mDeps.isAtLeastV()) {
7190 throw new IllegalStateException(
7191 "data saver status should be updated from platform");
7192 }
7193 ensureRunningOnConnectivityServiceThread();
7194 switch (intent.getAction()) {
7195 case ACTION_RESTRICT_BACKGROUND_CHANGED:
7196 // If the uid is present in the deny list, the API will consistently
7197 // return ENABLED. To retrieve the global switch status, the system
7198 // uid is chosen because it will never be included in the deny list.
7199 final int dataSaverForSystemUid =
7200 mPolicyManager.getRestrictBackgroundStatus(Process.SYSTEM_UID);
7201 final boolean isDataSaverEnabled = (dataSaverForSystemUid
7202 != ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED);
7203 mBpfNetMaps.setDataSaverEnabled(isDataSaverEnabled);
7204 break;
7205 default:
7206 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
7207 }
7208 }
7209 };
7210
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007211 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007212 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007213
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007214 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007215 public final String name;
7216 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007217 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007218 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007219
lifraf3a3492021-03-10 13:58:14 +08007220 NetworkProviderInfo(String name, Messenger messenger, int providerId,
7221 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007222 this.name = name;
7223 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007224 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007225 mDeathRecipient = deathRecipient;
7226
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007227 if (mDeathRecipient == null) {
7228 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007229 }
7230 }
7231
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007232 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09007233 try {
7234 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
7235 } catch (RemoteException e) {
7236 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007237 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09007238 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007239 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007240
James Mattis4fce5d12020-11-12 15:53:42 -08007241 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
7242 for (int i = 0; i < requests.size(); i++) {
7243 ensureNetworkRequestHasType(requests.get(i));
7244 }
7245 }
7246
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007247 private void ensureNetworkRequestHasType(NetworkRequest request) {
7248 if (request.type == NetworkRequest.Type.NONE) {
7249 throw new IllegalArgumentException(
7250 "All NetworkRequests in ConnectivityService must have a type");
7251 }
7252 }
7253
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007254 /**
7255 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08007256 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007257 */
James Mattis258ea3c2020-11-15 15:04:40 -08007258 @VisibleForTesting
7259 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08007260 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
7261 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08007262 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08007263
James Mattisa076c532020-12-02 14:12:41 -08007264 // mSatisfier and mActiveRequest rely on one another therefore set them together.
7265 void setSatisfier(
7266 @Nullable final NetworkAgentInfo satisfier,
7267 @Nullable final NetworkRequest activeRequest) {
7268 mSatisfier = satisfier;
7269 mActiveRequest = activeRequest;
7270 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007271
James Mattisd31bdfa2020-12-23 16:37:26 -08007272 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09007273 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09007274 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08007275 private NetworkAgentInfo mSatisfier;
7276 NetworkAgentInfo getSatisfier() {
7277 return mSatisfier;
7278 }
7279
7280 // The request in mRequests assigned to a network agent. This is null if none of the
7281 // requests in mRequests can be satisfied. This member has the constraint of only being
7282 // accessible on the handler thread.
7283 @Nullable
7284 private NetworkRequest mActiveRequest;
7285 NetworkRequest getActiveRequest() {
7286 return mActiveRequest;
7287 }
7288
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007289 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007290 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08007291 @Nullable
7292 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007293
7294 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08007295 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007296 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007297 final int mPid;
7298 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08007299 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007300 @Nullable
7301 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007302
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007303 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08007304 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007305
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007306 // Effective UID of this request. This is different from mUid when a privileged process
7307 // files a request on behalf of another UID. This UID is used to determine blocked status,
7308 // UID matching, and so on. mUid above is used for permission checks and to enforce the
7309 // maximum limit of registered callbacks per UID.
7310 final int mAsUid;
7311
paulhu48291862021-07-14 14:53:57 +08007312 // Preference order of this request.
7313 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08007314
James Mattis3ce3d3c2021-02-09 18:18:28 -08007315 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
7316 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
7317 // maintained for keying off of. This is only a concern when the original nri
7318 // mNetworkRequests changes which happens currently for apps that register callbacks to
7319 // track the default network. In those cases, the nri is updated to have mNetworkRequests
7320 // that match the per-app default nri that currently tracks the calling app's uid so that
7321 // callbacks are fired at the appropriate time. When the callbacks fire,
7322 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
7323 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
7324 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
7325 @NonNull
7326 private final NetworkRequest mNetworkRequestForCallback;
7327 NetworkRequest getNetworkRequestForCallback() {
7328 return mNetworkRequestForCallback;
7329 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007330
James Mattisd31bdfa2020-12-23 16:37:26 -08007331 /**
7332 * Get the list of UIDs this nri applies to.
7333 */
7334 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00007335 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08007336 // networkCapabilities.getUids() returns a defensive copy.
7337 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007338 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
7339 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08007340 }
7341
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007342 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
7343 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08007344 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08007345 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007346 }
7347
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007348 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007349 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08007350 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007351 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007352 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007353 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007354 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08007355 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007356 mBinder = null;
7357 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007358 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007359 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007360 mPerUidCounter = getRequestCounter(this);
7361 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007362 /**
7363 * Location sensitive data not included in pending intent. Only included in
7364 * {@link NetworkCallback}.
7365 */
7366 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007367 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007368 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007369 }
7370
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007371 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007372 @Nullable final IBinder binder,
7373 @NetworkCallback.Flag int callbackFlags,
7374 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007375 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
7376 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08007377 }
7378
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007379 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007380 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08007381 @Nullable final IBinder binder,
7382 @NetworkCallback.Flag int callbackFlags,
7383 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007384 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007385 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08007386 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007387 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08007388 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007389 mBinder = binder;
7390 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007391 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007392 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007393 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007394 mPerUidCounter = getRequestCounter(this);
7395 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007396 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08007397 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007398 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007399 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007400 }
7401
James Mattis3ce3d3c2021-02-09 18:18:28 -08007402 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
7403 @NonNull final List<NetworkRequest> r) {
7404 super();
7405 ensureAllNetworkRequestsHaveType(r);
7406 mRequests = initializeRequests(r);
7407 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007408 final NetworkAgentInfo satisfier = nri.getSatisfier();
7409 if (null != satisfier) {
7410 // If the old NRI was satisfied by an NAI, then it may have had an active request.
7411 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09007412 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09007413 // As this code creates a new NRI with a new set of requests, figure out which of
7414 // the list of requests should be the active request. It is always the first
7415 // request of the list that can be satisfied by the satisfier since the order of
7416 // requests is a priority order.
7417 // Note even in the presence of a satisfier there may not be an active request,
7418 // when the satisfier is the no-service network.
7419 NetworkRequest activeRequest = null;
7420 for (final NetworkRequest candidate : r) {
7421 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
7422 activeRequest = candidate;
7423 break;
7424 }
7425 }
7426 setSatisfier(satisfier, activeRequest);
7427 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007428 mMessenger = nri.mMessenger;
7429 mBinder = nri.mBinder;
7430 mPid = nri.mPid;
7431 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007432 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007433 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09007434 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09007435 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08007436 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007437 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08007438 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07007439 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08007440 }
7441
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007442 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08007443 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08007444 }
7445
paulhue9913722021-05-26 15:19:20 +08007446 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08007447 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08007448 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08007449 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08007450 }
7451
James Mattis2516da32021-01-31 17:06:19 -08007452 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
7453 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
7454 // false.
7455 boolean isBeingSatisfied() {
7456 return (null != mSatisfier && null != mActiveRequest);
7457 }
7458
James Mattis3d229892020-11-16 16:46:28 -08007459 boolean isMultilayerRequest() {
7460 return mRequests.size() > 1;
7461 }
7462
James Mattis45d81842021-01-10 14:24:24 -08007463 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
7464 // Creating a defensive copy to prevent the sender from modifying the list being
7465 // reflected in the return value of this method.
7466 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08007467 return Collections.unmodifiableList(tempRequests);
7468 }
7469
James Mattisb1392002021-03-31 13:57:52 -07007470 void linkDeathRecipient() {
7471 if (null != mBinder) {
7472 try {
7473 mBinder.linkToDeath(this, 0);
7474 } catch (RemoteException e) {
7475 binderDied();
7476 }
7477 }
7478 }
7479
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007480 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07007481 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09007482 try {
7483 mBinder.unlinkToDeath(this, 0);
7484 } catch (NoSuchElementException e) {
7485 // Temporary workaround for b/194394697 pending analysis of additional logs
7486 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
7487 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007488 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007489 }
7490
paulhu48291862021-07-14 14:53:57 +08007491 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
7492 // Compare two preference orders.
7493 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007494 }
7495
paulhu48291862021-07-14 14:53:57 +08007496 int getPreferenceOrderForNetd() {
7497 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
7498 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
7499 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08007500 }
paulhu48291862021-07-14 14:53:57 +08007501 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08007502 }
7503
James Mattis4fce5d12020-11-12 15:53:42 -08007504 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007505 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09007506 // As an immutable collection, mRequests cannot change by the time the
7507 // lambda is evaluated on the handler thread so calling .get() from a binder thread
7508 // is acceptable. Use handleReleaseNetworkRequest and not directly
7509 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
7510 // the app already unregistered the request.
7511 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
7512 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007513 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007514
James Mattis4fce5d12020-11-12 15:53:42 -08007515 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007516 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007517 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
7518 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08007519 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007520 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09007521 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08007522 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08007523 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08007524 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08007525 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007526 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007527 }
7528
Junyu Lai00d92df2022-07-05 11:01:52 +08007529 // Keep backward compatibility since the ServiceSpecificException is used by
7530 // the API surface, see {@link ConnectivityManager#convertServiceException}.
7531 public static class RequestInfoPerUidCounter extends PerUidCounter {
7532 RequestInfoPerUidCounter(int maxCountPerUid) {
7533 super(maxCountPerUid);
7534 }
7535
7536 @Override
7537 public synchronized void incrementCountOrThrow(int uid) {
7538 try {
7539 super.incrementCountOrThrow(uid);
7540 } catch (IllegalStateException e) {
7541 throw new ServiceSpecificException(
7542 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
7543 "Uid " + uid + " exceeded its allotted requests limit");
7544 }
7545 }
7546
7547 @Override
7548 public synchronized void decrementCountOrThrow(int uid) {
7549 throw new UnsupportedOperationException("Use decrementCount instead.");
7550 }
7551
7552 public synchronized void decrementCount(int uid) {
7553 try {
7554 super.decrementCountOrThrow(uid);
7555 } catch (IllegalStateException e) {
7556 logwtf("Exception when decrement per uid request count: ", e);
7557 }
7558 }
7559 }
7560
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007561 // This checks that the passed capabilities either do not request a
7562 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007563 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007564 int callerPid, int callerUid, String callerPackageName) {
Junyu Lai71b51532024-02-01 10:39:01 +08007565 if (null != nc.getSsid() && !hasSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007566 throw new SecurityException("Insufficient permissions to request a specific SSID");
7567 }
paulhu1a407652019-03-22 16:35:06 +08007568
7569 if (nc.hasSignalStrength()
Junyu Lai71b51532024-02-01 10:39:01 +08007570 && !hasNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
paulhu1a407652019-03-22 16:35:06 +08007571 throw new SecurityException(
7572 "Insufficient permissions to request a specific signal strength");
7573 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08007574 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07007575
Ying Xu7cabd322024-01-15 18:40:15 -08007576 if (nc.getSubscriptionIds().isEmpty()) {
7577 return;
Benedict Wong53de25f2021-03-24 14:01:51 -07007578 }
Ying Xu7cabd322024-01-15 18:40:15 -08007579 if (mRequestRestrictedWifiEnabled
7580 && canRequestRestrictedNetworkDueToCarrierPrivileges(nc, callerUid)) {
7581 return;
7582 }
7583 enforceNetworkFactoryPermission();
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007584 }
7585
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007586 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007587 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007588 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08007589 // mNetworkRequests may contain the same value multiple times in case of
7590 // multilayer requests. It won't matter in this case because the thresholds
7591 // will then be the same and be deduplicated as they enter the `thresholds` set.
7592 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08007593 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7594 for (final NetworkRequest req : nri.mRequests) {
7595 if (req.networkCapabilities.hasSignalStrength()
7596 && nai.satisfiesImmutableCapabilitiesOf(req)) {
7597 thresholds.add(req.networkCapabilities.getSignalStrength());
7598 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007599 }
7600 }
7601 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09007602 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007603 }
7604
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007605 private void updateSignalStrengthThresholds(
7606 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007607 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007608
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007609 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007610 String detail;
7611 if (request != null && request.networkCapabilities.hasSignalStrength()) {
7612 detail = reason + " " + request.networkCapabilities.getSignalStrength();
7613 } else {
7614 detail = reason;
7615 }
7616 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007617 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09007618 }
7619
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007620 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09007621 }
7622
Chalard Jeandd421992021-12-16 23:16:02 +09007623 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07007624 if (nc == null) {
7625 return;
7626 }
7627 NetworkSpecifier ns = nc.getNetworkSpecifier();
7628 if (ns == null) {
7629 return;
7630 }
lucaslin22f9b9f2021-01-22 15:15:23 +08007631 if (ns instanceof MatchAllNetworkSpecifier) {
7632 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
7633 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07007634 }
7635
Chalard Jeandd421992021-12-16 23:16:02 +09007636 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08007637 ensureValidNetworkSpecifier(nc);
7638 if (nc.isPrivateDnsBroken()) {
7639 throw new IllegalArgumentException("Can't request broken private DNS");
7640 }
Chalard Jeande665262022-02-25 16:12:12 +09007641 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09007642 throw new IllegalArgumentException("Can't request access UIDs");
7643 }
lucasline117e2e2019-10-22 18:27:33 +08007644 }
7645
Chalard Jeandd421992021-12-16 23:16:02 +09007646 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
7647 ensureListenableCapabilities(nc);
7648 final String badCapability = nc.describeFirstNonRequestableCapability();
7649 if (badCapability != null) {
7650 throw new IllegalArgumentException("Cannot request network with " + badCapability);
7651 }
7652 }
7653
Chiachang Wang3bc52762021-11-25 14:17:57 +08007654 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
7655 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08007656 private boolean isTargetSdkAtleast(int version, int callingUid,
7657 @NonNull String callingPackageName) {
7658 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08007659 final PackageManager pm =
7660 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08007661 try {
Roshan Pius951c0032020-12-22 15:10:42 -08007662 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08007663 if (callingVersion < version) return false;
7664 } catch (PackageManager.NameNotFoundException e) { }
7665 return true;
7666 }
7667
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007668 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007669 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09007670 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007671 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08007672 @Nullable String callingAttributionTag) {
Junyu Lai71b51532024-02-01 10:39:01 +08007673 if (legacyType != TYPE_NONE && !hasNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08007674 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
7675 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08007676 throw new SecurityException("Insufficient permissions to specify legacy type");
7677 }
markchienfac84a22020-03-18 21:16:15 +08007678 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007679 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007680 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007681 // Privileged callers can track the default network of another UID by passing in a UID.
7682 if (asUid != Process.INVALID_UID) {
7683 enforceSettingsPermission();
7684 } else {
7685 asUid = callingUid;
7686 }
junyulaiad010792021-01-11 16:53:38 +08007687 final NetworkRequest.Type reqType;
7688 try {
7689 reqType = NetworkRequest.Type.values()[reqTypeInt];
7690 } catch (ArrayIndexOutOfBoundsException e) {
7691 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
7692 }
7693 switch (reqType) {
7694 case TRACK_DEFAULT:
7695 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007696 // is unused and will be replaced by ones appropriate for the UID (usually, the
7697 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007698 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007699 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08007700 enforceAccessPermission();
7701 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007702 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00007703 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007704 networkCapabilities = new NetworkCapabilities(defaultNc);
7705 break;
Junyu Laia62493f2021-01-19 11:10:56 +00007706 case BACKGROUND_REQUEST:
7707 enforceNetworkStackOrSettingsPermission();
7708 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08007709 case REQUEST:
7710 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7711 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007712 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08007713 // TODO: this is incorrect. We mark the request as metered or not depending on
7714 // the state of the app when the request is filed, but we never change the
7715 // request if the app changes network state. http://b/29964605
7716 enforceMeteredApnPolicy(networkCapabilities);
7717 break;
junyulai1b1c8742021-03-12 20:05:08 +08007718 case LISTEN_FOR_BEST:
7719 enforceAccessPermission();
7720 networkCapabilities = new NetworkCapabilities(networkCapabilities);
7721 break;
junyulaiad010792021-01-11 16:53:38 +08007722 default:
7723 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09007724 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007725 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007726 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007727 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007728
junyulai1b1c8742021-03-12 20:05:08 +08007729 // Enforce FOREGROUND if the caller does not have permission to use background network.
7730 if (reqType == LISTEN_FOR_BEST) {
7731 restrictBackgroundRequestForCaller(networkCapabilities);
7732 }
7733
7734 // Set the UID range for this request to the single UID of the requester, unless the
7735 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007736 // This will overwrite any allowed UIDs in the requested capabilities. Though there
7737 // are no visible methods to set the UIDs, an app could use reflection to try and get
7738 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08007739 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08007740 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7741 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07007742
Etan Cohen85000162017-02-05 10:42:27 -08007743 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007744 throw new IllegalArgumentException("Bad timeout specified");
7745 }
Etan Cohen9786d922015-11-18 10:56:15 -08007746
James Mattis3ce3d3c2021-02-09 18:18:28 -08007747 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08007748 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007749 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09007750 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007751 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007752 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007753
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007754 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
7755 // copied from the default request above. (This is necessary to ensure, for example, that
7756 // the callback does not leak sensitive information to unprivileged apps.) Check that the
7757 // changes don't alter request matching.
7758 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
7759 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09007760 throw new IllegalStateException(
7761 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09007762 + networkCapabilities + " vs. " + defaultNc);
7763 }
7764
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007765 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007766 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007767 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07007768 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007769 }
7770 return networkRequest;
7771 }
7772
James Mattis3ce3d3c2021-02-09 18:18:28 -08007773 /**
7774 * Return the nri to be used when registering a network request. Specifically, this is used with
7775 * requests registered to track the default request. If there is currently a per-app default
7776 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
7777 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007778 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7779 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007780 * @param nr the network request for the nri.
7781 * @param msgr the messenger for the nri.
7782 * @param binder the binder for the nri.
7783 * @param callingAttributionTag the calling attribution tag for the nri.
7784 * @return the nri to register.
7785 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007786 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007787 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08007788 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08007789 @Nullable String callingAttributionTag) {
7790 final List<NetworkRequest> requests;
7791 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
7792 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007793 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08007794 } else {
7795 requests = Collections.singletonList(nr);
7796 }
Roshan Pius951c0032020-12-22 15:10:42 -08007797 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007798 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007799 }
7800
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007801 private boolean shouldCheckCapabilitiesDeclaration(
7802 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
7803 @NonNull final String callingPackageName) {
7804 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
7805 // Only run the check if the change is enabled.
7806 if (!mDeps.isChangeEnabled(
7807 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
7808 callingPackageName, user)) {
7809 return false;
7810 }
7811
7812 return networkCapabilities.hasCapability(
7813 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7814 || networkCapabilities.hasCapability(
7815 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7816 }
7817
7818 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007819 @NonNull final NetworkCapabilities networkCapabilities, int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007820 // This check is added to fix the linter error for "current min is 30", which is not going
7821 // to happen because Connectivity service always run in S+.
Chalard Jeandf29a852023-05-29 17:02:43 +09007822 if (!mDeps.isAtLeastS()) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007823 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7824 return;
7825 }
7826 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007827 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007828 try {
7829 synchronized (mSelfCertifiedCapabilityCache) {
7830 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7831 callerPackageName);
7832 if (applicationNetworkCapabilities == null) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007833 final PackageManager packageManager =
7834 mContext.createContextAsUser(UserHandle.getUserHandleForUid(
7835 callingUid), 0 /* flags */).getPackageManager();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007836 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7837 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7838 callerPackageName
7839 );
7840 final XmlResourceParser parser = packageManager
7841 .getResourcesForApplication(callerPackageName)
7842 .getXml(networkSliceProperty.getResourceId());
7843 applicationNetworkCapabilities =
7844 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7845 mSelfCertifiedCapabilityCache.put(callerPackageName,
7846 applicationNetworkCapabilities);
7847 }
7848
7849 }
7850 } catch (PackageManager.NameNotFoundException ne) {
7851 throw new SecurityException(
7852 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7853 + " property");
7854 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7855 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007856 } finally {
7857 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007858 }
7859
7860 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7861 networkCapabilities);
7862 }
Ying Xu7cabd322024-01-15 18:40:15 -08007863
7864 private boolean canRequestRestrictedNetworkDueToCarrierPrivileges(
7865 NetworkCapabilities networkCapabilities, int callingUid) {
7866 if (mRequestRestrictedWifiEnabled) {
7867 // For U+ devices, callers with carrier privilege could request restricted networks
7868 // with CBS capabilities, or any restricted WiFi networks.
7869 return ((networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7870 || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))
7871 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities));
7872 } else {
7873 // For T+ devices, callers with carrier privilege could request with CBS
7874 // capabilities.
7875 return (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7876 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities));
7877 }
7878 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007879 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007880 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007881 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7882 callingPackageName)) {
Yuyang Huang4c7deee2023-11-28 15:29:00 +09007883 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities,
7884 callingUid);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007885 }
Ying Xu7cabd322024-01-15 18:40:15 -08007886 if (!networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
7887 if (!canRequestRestrictedNetworkDueToCarrierPrivileges(
7888 networkCapabilities, callingUid)) {
7889 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007890 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007891 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007892 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007893 }
7894 }
7895
fenglu3f357402015-03-20 11:29:56 -07007896 @Override
fenglub00f4882015-04-21 17:12:05 -07007897 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007898 enforceAccessPermission();
7899 NetworkAgentInfo nai = null;
7900 if (network == null) {
7901 return false;
7902 }
7903 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007904 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007905 }
7906 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007907 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007908 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007909 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007910 Integer uidReqs = mBandwidthRequests.get(uid);
7911 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007912 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007913 }
7914 mBandwidthRequests.put(uid, ++uidReqs);
7915 }
fenglu3f357402015-03-20 11:29:56 -07007916 return true;
7917 }
7918 return false;
7919 }
7920
Felipe Leme0a5ae422016-06-20 16:36:29 -07007921 private boolean isSystem(int uid) {
7922 return uid < Process.FIRST_APPLICATION_UID;
7923 }
fenglu3f357402015-03-20 11:29:56 -07007924
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007925 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007926 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007927 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007928 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007929 return;
7930 }
Hugo Benichi39621362017-02-11 17:04:43 +09007931 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7932 // Policy already enforced.
7933 return;
7934 }
paulhuaf50d7d2020-12-24 19:47:34 +08007935 final long ident = Binder.clearCallingIdentity();
7936 try {
7937 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7938 // If UID is restricted, don't allow them to bring up metered APNs.
7939 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7940 }
7941 } finally {
7942 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007943 }
7944 }
7945
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007946 @Override
7947 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007948 PendingIntent operation, @NonNull String callingPackageName,
7949 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007950 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007951 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007952 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007953 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007954 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007955 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007956 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007957 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007958 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007959 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7960 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007961
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007962 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007963 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007964 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7965 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007966 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007967 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7968 nri));
7969 return networkRequest;
7970 }
7971
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007972 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7973 mHandler.sendMessageDelayed(
7974 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007975 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007976 }
7977
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007978 @Override
7979 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007980 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007981 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007982 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007983 }
7984
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007985 // In order to implement the compatibility measure for pre-M apps that call
7986 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7987 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7988 // This ensures it has permission to do so.
7989 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7990 if (nc == null) {
7991 return false;
7992 }
7993 int[] transportTypes = nc.getTransportTypes();
7994 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7995 return false;
7996 }
7997 try {
7998 mContext.enforceCallingOrSelfPermission(
7999 android.Manifest.permission.ACCESS_WIFI_STATE,
8000 "ConnectivityService");
8001 } catch (SecurityException e) {
8002 return false;
8003 }
8004 return true;
8005 }
8006
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008007 @Override
8008 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08008009 Messenger messenger, IBinder binder,
8010 @NetworkCallback.Flag int callbackFlags,
8011 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008012 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09008013 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
8014 enforceAccessPermission();
8015 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008016
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008017 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008018 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008019 Binder.getCallingPid(), callingUid, callingPackageName);
8020 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09008021 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
8022 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
8023 // onLost and onAvailable callbacks when networks move in and out of the background.
8024 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
8025 // can't request networks.
8026 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09008027 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07008028
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008029 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09008030 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08008031 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008032 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08008033 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09008034 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008035
8036 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
8037 return networkRequest;
8038 }
8039
8040 @Override
8041 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08008042 PendingIntent operation, @NonNull String callingPackageName,
8043 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00008044 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008045 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04008046 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
8047 enforceAccessPermission();
8048 }
Chalard Jeandd421992021-12-16 23:16:02 +09008049 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09008050 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08008051 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09008052 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08008053 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09008054
8055 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09008056 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008057 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
8058 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09008059 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04008060
WeiZhang1cc3f172021-06-03 19:02:04 -05008061 mHandler.sendMessage(mHandler.obtainMessage(
8062 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008063 }
8064
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008065 /** Returns the next Network provider ID. */
8066 public final int nextNetworkProviderId() {
8067 return mNextNetworkProviderId.getAndIncrement();
8068 }
8069
Erik Kline0c04b742016-07-07 16:50:58 +09008070 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008071 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09008072 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09008073 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09008074 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008075 }
8076
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008077 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
8078 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008079 // Avoid creating duplicates. even if an app makes a direct AIDL call.
8080 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
8081 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08008082 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008083 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008084 return;
8085 }
8086
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008087 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
8088 mNetworkProviderInfos.put(npi.messenger, npi);
8089 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008090 }
8091
8092 @Override
8093 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008094 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08008095 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008096 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08008097 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008098 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
8099 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008100 }
8101
8102 @Override
8103 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008104 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008105 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008106 }
8107
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008108 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09008109 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008110 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
8111 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09008112 Objects.requireNonNull(score);
8113 Objects.requireNonNull(caps);
8114 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008115 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008116 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09008117 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
8118 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008119 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
8120 }
8121
Chalard Jeanbb902a52021-08-18 01:35:19 +09008122 private void updateOfferScore(final NetworkOffer offer) {
8123 final boolean yieldToBadWiFi =
8124 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
8125 final NetworkOffer newOffer = new NetworkOffer(
8126 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
8127 offer.caps, offer.callback, offer.providerId);
8128 if (offer.equals(newOffer)) return;
8129 handleRegisterNetworkOffer(newOffer);
8130 }
8131
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008132 @Override
8133 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08008134 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008135 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
8136 }
8137
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008138 private void handleUnregisterNetworkProvider(Messenger messenger) {
8139 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
8140 if (npi == null) {
8141 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07008142 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008143 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008144 // Unregister all the offers from this provider
8145 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
8146 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09008147 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008148 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
8149 toRemove.add(noi);
8150 }
8151 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09008152 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008153 handleUnregisterNetworkOffer(noi);
8154 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008155 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07008156 }
8157
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008158 @Override
James Mattisf7027322020-12-13 16:28:14 -08008159 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08008160 if (request.hasTransport(TRANSPORT_TEST)) {
8161 enforceNetworkFactoryOrTestNetworksPermission();
8162 } else {
8163 enforceNetworkFactoryPermission();
8164 }
James Mattisf7027322020-12-13 16:28:14 -08008165 final NetworkRequestInfo nri = mNetworkRequests.get(request);
8166 if (nri != null) {
8167 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
8168 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
8169 mHandler.post(() -> handleReleaseNetworkRequest(
8170 nri.mRequests.get(0), mDeps.getCallingUid(), true));
8171 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09008172 }
8173
Paul Jensen1f567382015-02-13 14:18:39 -05008174 // NOTE: Accessed on multiple threads, must be synchronized on itself.
8175 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008176 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05008177 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008178 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05008179 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09008180 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008181
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008182 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05008183 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008184 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008185
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008186 // UID ranges for users that are currently blocked by VPNs.
8187 // This array is accessed and iterated on multiple threads without holding locks, so its
8188 // contents must never be mutated. When the ranges change, the array is replaced with a new one
8189 // (on the handler thread).
8190 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
8191
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008192 // Must only be accessed on the handler thread
8193 @NonNull
8194 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
8195
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008196 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008197 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09008198
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008199 // Current OEM network preferences. This object must only be written to on the handler thread.
8200 // Since it is immutable and always non-null, other threads may read it if they only care
8201 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08008202 @NonNull
8203 private OemNetworkPreferences mOemNetworkPreferences =
8204 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09008205 // Current per-profile network preferences. This object follows the same threading rules as
8206 // the OEM network preferences above.
8207 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09008208 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
8209 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08008210
lucaslin3ba7cc22022-12-19 02:35:33 +00008211 // Current VPN network preferences. This object follows the same threading rules as the OEM
8212 // network preferences above.
8213 @NonNull
8214 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
8215 mVpnNetworkPreferences = new NetworkPreferenceList<>();
8216
paulhu51f77dc2021-06-07 02:34:20 +00008217 // A set of UIDs that should use mobile data preferentially if available. This object follows
8218 // the same threading rules as the OEM network preferences above.
8219 @NonNull
8220 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
8221
James Mattiscb1e0362021-04-06 17:07:42 -07008222 // OemNetworkPreferences activity String log entries.
8223 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
8224 @NonNull
8225 private final LocalLog mOemNetworkPreferencesLogs =
8226 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
8227
James Mattis02220e22021-03-13 19:27:21 -08008228 /**
8229 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
8230 * @param packageName the package name to check existence of a mapping for.
8231 * @return true if a mapping exists, false otherwise
8232 */
8233 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
8234 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
8235 }
8236
James Mattise3ef1912020-12-20 11:09:58 -08008237 // The always-on request for an Internet-capable network that apps without a specific default
8238 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08008239 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09008240 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008241 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08008242 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08008243 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08008244 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08008245 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09008246
James Mattisd31bdfa2020-12-23 16:37:26 -08008247 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
8248 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
8249 }
8250
8251 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08008252 * Return the default network request currently tracking the given uid.
8253 * @param uid the uid to check.
8254 * @return the NetworkRequestInfo tracking the given uid.
8255 */
8256 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08008257 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008258 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008259 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008260 // Checking the first request is sufficient as only multilayer requests will have more
8261 // than one request and for multilayer, all requests will track the same uids.
8262 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08008263 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08008264 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008265 highestPriorityNri = nri;
8266 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08008267 }
8268 }
paulhuaa0743d2021-05-26 21:56:03 +08008269 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08008270 }
8271
8272 /**
8273 * Get a copy of the network requests of the default request that is currently tracking the
8274 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008275 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8276 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008277 * @param requestorUid the uid to check the default for.
8278 * @param requestorPackageName the requestor's package name.
8279 * @return a copy of the default's NetworkRequest that is tracking the given uid.
8280 */
8281 @NonNull
8282 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008283 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008284 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008285 getDefaultRequestTrackingUid(asUid).mRequests,
8286 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008287 }
8288
8289 /**
8290 * Copy the given nri's NetworkRequest collection.
8291 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008292 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
8293 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008294 * @param requestorUid the uid to set on the copied collection.
8295 * @param requestorPackageName the package name to set on the copied collection.
8296 * @return the copied NetworkRequest collection.
8297 */
8298 @NonNull
8299 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008300 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
8301 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08008302 final List<NetworkRequest> requests = new ArrayList<>();
8303 for (final NetworkRequest nr : requestsToCopy) {
8304 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008305 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08008306 nr.legacyType, nextNetworkRequestId(), nr.type));
8307 }
8308 return requests;
8309 }
8310
8311 @NonNull
8312 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008313 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
8314 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09008315 // These capabilities are for a TRACK_DEFAULT callback, so:
8316 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
8317 // mDefaultRequest and a per-UID default request.
8318 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008319 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09008320 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008321 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
8322 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09008323 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08008324 restrictRequestUidsForCallerAndSetRequestorInfo(
8325 netCap, requestorUid, requestorPackageName);
8326 return netCap;
8327 }
8328
8329 /**
8330 * Get the nri that is currently being tracked for callbacks by per-app defaults.
8331 * @param nr the network request to check for equality against.
8332 * @return the nri if one exists, null otherwise.
8333 */
8334 @Nullable
8335 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
8336 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
8337 if (nri.getNetworkRequestForCallback().equals(nr)) {
8338 return nri;
8339 }
8340 }
8341 return null;
8342 }
8343
8344 /**
8345 * Check if an nri is currently being managed by per-app default networking.
8346 * @param nri the nri to check.
8347 * @return true if this nri is currently being managed by per-app default networking.
8348 */
8349 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
8350 // nri.mRequests.get(0) is only different from the original request filed in
8351 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
8352 // functionality therefore if these two don't match, it means this particular nri is
8353 // currently being managed by a per-app default.
8354 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
8355 }
8356
8357 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08008358 * Determine if an nri is a managed default request that disallows default networking.
8359 * @param nri the request to evaluate
8360 * @return true if device-default networking is disallowed
8361 */
8362 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
8363 // Check if this nri is a managed default that supports the default network at its
8364 // lowest priority request.
8365 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
8366 final NetworkCapabilities lowestPriorityNetCap =
8367 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
8368 return isPerAppDefaultRequest(nri)
8369 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
8370 lowestPriorityNetCap));
8371 }
8372
Erik Kline05f2b402015-04-30 12:58:40 +09008373 // Request used to optionally keep mobile data active even when higher
8374 // priority networks like Wi-Fi are active.
8375 private final NetworkRequest mDefaultMobileDataRequest;
8376
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07008377 // Request used to optionally keep wifi data active even when higher
8378 // priority networks like ethernet are active.
8379 private final NetworkRequest mDefaultWifiRequest;
8380
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08008381 // Request used to optionally keep vehicle internal network always active
8382 private final NetworkRequest mDefaultVehicleRequest;
8383
James Mattisd31bdfa2020-12-23 16:37:26 -08008384 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
8385 // network with no service. This NAI should never be matched against, nor should any public API
8386 // ever return the associated network. For this reason, this NAI is not in the list of available
8387 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
8388 // default requests that don't support using the device default network which will ultimately
8389 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
8390 @VisibleForTesting
8391 final NetworkAgentInfo mNoServiceNetwork;
8392
Chalard Jean5b409c72021-02-04 13:12:59 +09008393 // The NetworkAgentInfo currently satisfying the default request, if any.
8394 private NetworkAgentInfo getDefaultNetwork() {
8395 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09008396 }
8397
James Mattis2516da32021-01-31 17:06:19 -08008398 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08008399 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08008400 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8401 // Currently, all network requests will have the same uids therefore checking the first
8402 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008403 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08008404 if (null == uids) {
8405 continue;
8406 }
8407 for (final UidRange range : uids) {
8408 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08008409 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08008410 highestPriorityNri = nri;
8411 }
James Mattis2516da32021-01-31 17:06:19 -08008412 }
8413 }
8414 }
Hansen Kurlied972a62023-09-07 16:26:02 +08008415 if (!highestPriorityNri.isBeingSatisfied()) return null;
paulhuaa0743d2021-05-26 21:56:03 +08008416 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08008417 }
8418
Varun Ananddf569952019-02-06 10:13:38 -08008419 @Nullable
8420 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
8421 return nai != null ? nai.network : null;
8422 }
8423
8424 private void ensureRunningOnConnectivityServiceThread() {
8425 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
8426 throw new IllegalStateException(
8427 "Not running on ConnectivityService thread: "
8428 + Thread.currentThread().getName());
8429 }
8430 }
8431
Chalard Jean3a3f5f22019-04-10 23:07:55 +09008432 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09008433 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
8434 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07008435 }
8436
Chalard Jean29d06db2018-05-02 21:14:54 +09008437 /**
Chalard Jeane0aaca52023-10-17 13:23:07 +09008438 * Returns whether local agents are supported on this device.
8439 *
8440 * Local agents are supported from U on TVs, and from V on all devices.
8441 */
8442 @VisibleForTesting
8443 public boolean areLocalAgentsSupported() {
8444 final PackageManager pm = mContext.getPackageManager();
8445 // Local agents are supported starting on U on TVs and on V on everything else.
8446 return mDeps.isAtLeastV() || (mDeps.isAtLeastU() && pm.hasSystemFeature(FEATURE_LEANBACK));
8447 }
8448
8449 /**
Chalard Jean29d06db2018-05-02 21:14:54 +09008450 * Register a new agent with ConnectivityService to handle a network.
8451 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008452 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09008453 * @param networkInfo the initial info associated with this network. It can be updated later :
8454 * see {@link #updateNetworkInfo}.
8455 * @param linkProperties the initial link properties of this network. They can be updated
8456 * later : see {@link #updateLinkProperties}.
8457 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09008458 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008459 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008460 * @param localNetworkConfig config about this local network, or null if not a local network
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008461 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008462 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008463 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09008464 */
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008465 public Network registerNetworkAgent(INetworkAgent na,
8466 NetworkInfo networkInfo,
8467 LinkProperties linkProperties,
8468 NetworkCapabilities networkCapabilities,
8469 @NonNull NetworkScore initialScore,
8470 @Nullable LocalNetworkConfig localNetworkConfig,
8471 NetworkAgentConfig networkAgentConfig,
Chalard Jean28018572020-12-21 18:36:52 +09008472 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008473 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
8474 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
8475 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09008476 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09008477 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09008478 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08008479 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008480 } else {
8481 enforceNetworkFactoryPermission();
8482 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09008483 final boolean hasLocalCap =
8484 networkCapabilities.hasCapability(NET_CAPABILITY_LOCAL_NETWORK);
8485 if (hasLocalCap && !areLocalAgentsSupported()) {
8486 // Before U, netd doesn't support PHYSICAL_LOCAL networks so this can't work.
8487 throw new IllegalArgumentException("Local agents are not supported in this version");
8488 }
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008489 final boolean hasLocalNetworkConfig = null != localNetworkConfig;
8490 if (hasLocalCap != hasLocalNetworkConfig) {
8491 throw new IllegalArgumentException(null != localNetworkConfig
8492 ? "Only local network agents can have a LocalNetworkConfig"
8493 : "Local network agents must have a LocalNetworkConfig"
8494 );
8495 }
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008496
Lorenzo Colittif61ca942020-12-15 11:02:22 +09008497 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008498 final long token = Binder.clearCallingIdentity();
8499 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008500 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008501 networkCapabilities, initialScore, networkAgentConfig, localNetworkConfig,
8502 providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008503 } finally {
8504 Binder.restoreCallingIdentity(token);
8505 }
8506 }
8507
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008508 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008509 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008510 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig,
8511 @Nullable LocalNetworkConfig localNetworkConfig, int providerId,
Chalard Jean28018572020-12-21 18:36:52 +09008512 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008513
Chalard Jeandbc46952022-02-02 00:14:18 +09008514 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
8515 // and mutate them at any time.
8516 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
8517 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
8518 final LinkProperties lpCopy = new LinkProperties(linkProperties);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008519 // No need to copy |localNetworkConfiguration| as it is immutable.
Chalard Jeandbc46952022-02-02 00:14:18 +09008520
Chalard Jean366c5252022-01-25 18:27:53 +09008521 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09008522 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09008523 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
8524 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008525 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09008526 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09008527 localNetworkConfig, currentScore, mContext, mTrackerHandler,
8528 new NetworkAgentConfig(networkAgentConfig), this, mNetd, mDnsResolver, providerId,
8529 uid, mLingerDelayMs, mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008530
Chalard Jeandbc46952022-02-02 00:14:18 +09008531 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09008532 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09008533 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008534 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09008535 mDeps.getNetworkStack().makeNetworkMonitor(
8536 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008537 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
8538 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008539 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008540 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09008541 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008542 }
8543
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008544 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09008545 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008546 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09008547 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09008548 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09008549 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
8550 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
8551 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09008552
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008553 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09008554
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008555 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008556 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008557 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05008558 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008559
8560 try {
8561 networkMonitor.start();
8562 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08008563 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09008564 }
Chalard Jean366c5252022-01-25 18:27:53 +09008565
Chalard Jean1e4c2182023-10-06 18:45:53 +09008566 if (nai.isLocalNetwork()) {
Chalard Jean22350c92023-10-07 19:21:45 +09008567 handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
Chalard Jean1e4c2182023-10-06 18:45:53 +09008568 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008569 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09008570 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09008571 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008572 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008573 }
8574
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008575 private class NetworkOfferInfo implements IBinder.DeathRecipient {
8576 @NonNull public final NetworkOffer offer;
8577
8578 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
8579 this.offer = offer;
8580 }
8581
8582 @Override
8583 public void binderDied() {
8584 mHandler.post(() -> handleUnregisterNetworkOffer(this));
8585 }
8586 }
8587
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008588 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
8589 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
8590 if (npi.providerId == providerId) return true;
8591 }
8592 return false;
8593 }
8594
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008595 /**
8596 * Register or update a network offer.
8597 * @param newOffer The new offer. If the callback member is the same as an existing
8598 * offer, it is an update of that offer.
8599 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09008600 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008601 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
8602 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09008603 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008604 // This may actually happen if a provider updates its score or registers and then
8605 // immediately unregisters. The offer would still be in the handler queue, but the
8606 // provider would have been removed.
8607 if (DBG) log("Received offer from an unregistered provider");
8608 return;
8609 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008610 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
8611 if (null != existingOffer) {
8612 handleUnregisterNetworkOffer(existingOffer);
8613 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09008614 if (DBG) {
8615 // handleUnregisterNetworkOffer has already logged the old offer
8616 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
8617 }
8618 } else {
8619 if (DBG) {
8620 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
8621 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008622 }
8623 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
8624 try {
Chalard Jean30689b82021-03-22 22:44:02 +09008625 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008626 } catch (RemoteException e) {
8627 noi.binderDied();
8628 return;
8629 }
8630 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09008631 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008632 }
8633
8634 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
8635 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09008636 if (DBG) {
8637 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
8638 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07008639
8640 // If the provider removes the offer and dies immediately afterwards this
8641 // function may be called twice in a row, but the array will no longer contain
8642 // the offer.
8643 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09008644 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008645 }
8646
8647 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
8648 @NonNull final INetworkOfferCallback callback) {
8649 ensureRunningOnConnectivityServiceThread();
8650 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09008651 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09008652 }
8653 return null;
8654 }
8655
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008656 /**
8657 * Called when receiving LinkProperties directly from a NetworkAgent.
8658 * Stores into |nai| any data coming from the agent that might also be written to the network's
8659 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
8660 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09008661 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008662 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008663 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
8664 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09008665 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08008666 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008667 }
8668
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008669 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08008670 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008671 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008672
Lorenzo Colittid523d142020-04-01 20:16:30 +09008673 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
8674 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
8675 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09008676 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09008677
Suprabh Shukla1e312032023-01-24 03:36:37 -08008678 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008679
8680 // update filtering rules, need to happen after the interface update so netd knows about the
8681 // new interface (the interface name -> index map becomes initialized)
8682 updateVpnFiltering(newLp, oldLp, networkAgent);
8683
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008684 updateMtu(newLp, oldLp);
8685 // TODO - figure out what to do for clat
8686// for (LinkProperties lp : newLp.getStackedLinks()) {
8687// updateMtu(lp, null);
8688// }
Chalard Jean5b409c72021-02-04 13:12:59 +09008689 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008690 mProxyTracker.updateDefaultNetworkProxyPortForPAC(newLp, null);
lucaslin821c9782018-11-28 19:27:52 +08008691 updateTcpBufferSizes(newLp.getTcpBufferSizes());
8692 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008693
Erik Klineb9888902016-04-05 13:30:49 +09008694 updateRoutes(newLp, oldLp, netId);
8695 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05008696 // Make sure LinkProperties represents the latest private DNS status.
8697 // This does not need to be done before updateDnses because the
8698 // LinkProperties are not the source of the private DNS configuration.
8699 // updateDnses will fetch the private DNS configuration from DnsManager.
8700 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09008701
Chalard Jean5b409c72021-02-04 13:12:59 +09008702 if (isDefaultNetwork(networkAgent)) {
Aaron Huang9fe47be2021-06-08 13:11:45 +08008703 mProxyTracker.setDefaultProxy(newLp.getHttpProxy());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008704 } else if (networkAgent.everConnected()) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09008705 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05008706 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008707
8708 updateWakeOnLan(newLp);
8709
Hai Shalome58bdc62021-01-11 18:45:34 -08008710 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
8711 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
8712 // does, it needs to be merged here.
8713 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
8714 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09008715
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008716 // TODO - move this check to cover the whole function
8717 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09008718 synchronized (networkAgent) {
8719 networkAgent.linkProperties = newLp;
8720 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09008721 // Start or stop DNS64 detection and 464xlat according to network state.
8722 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08008723 // Notify NSS when relevant events happened. Currently, NSS only cares about
8724 // interface changed to update clat interfaces accounting.
8725 final boolean interfacesChanged = oldLp == null
8726 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
8727 if (interfacesChanged) {
8728 notifyIfacesChangedForNetworkStats();
8729 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09008730 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
8731 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09008732 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008733 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09008734
8735 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04008736 }
8737
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +09008738 private void applyInitialLinkProperties(@NonNull NetworkAgentInfo nai) {
8739 updateLinkProperties(nai, new LinkProperties(nai.linkProperties), null);
8740 }
8741
Hai Shalome58bdc62021-01-11 18:45:34 -08008742 /**
8743 * @param naData captive portal data from NetworkAgent
8744 * @param apiData captive portal data from capport API
8745 */
8746 @Nullable
8747 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
8748 CaptivePortalData apiData) {
8749 if (naData == null || apiData == null) {
8750 return naData == null ? apiData : naData;
8751 }
8752 final CaptivePortalData.Builder captivePortalBuilder =
8753 new CaptivePortalData.Builder(naData);
8754
8755 if (apiData.isCaptive()) {
8756 captivePortalBuilder.setCaptive(true);
8757 }
8758 if (apiData.isSessionExtendable()) {
8759 captivePortalBuilder.setSessionExtendable(true);
8760 }
8761 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
8762 // Expiry time, bytes remaining, refresh time all need to come from the same source,
8763 // otherwise data would be inconsistent. Prefer the capport API info if present,
8764 // as it can generally be refreshed more often.
8765 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
8766 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
8767 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
8768 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
8769 // No source has time / bytes remaining information: surface the newest refresh time
8770 // for other fields
8771 captivePortalBuilder.setRefreshTime(
8772 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
8773 }
8774
Hai Shalom7c6ab402021-02-04 19:34:06 -08008775 // Prioritize the user portal URL from the network agent if the source is authenticated.
8776 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
8777 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8778 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
8779 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008780 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08008781 // Prioritize the venue information URL from the network agent if the source is
8782 // authenticated.
8783 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
8784 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
8785 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
8786 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08008787 }
8788 return captivePortalBuilder.build();
8789 }
8790
Suprabh Shukla53e16392023-04-26 18:47:36 -07008791 @VisibleForTesting
8792 static String makeNflogPrefix(String iface, long networkHandle) {
Suprabh Shukla1e312032023-01-24 03:36:37 -08008793 // This needs to be kept in sync and backwards compatible with the decoding logic in
8794 // NetdEventListenerService, which is non-mainline code.
8795 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
8796 }
8797
Suprabh Shukla75642282023-04-25 23:15:43 -07008798 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
8799 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
8800 return true;
8801 }
8802 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
8803 return true;
8804 }
8805 return false;
8806 }
8807
Suprabh Shukla1e312032023-01-24 03:36:37 -08008808 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09008809 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09008810 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07008811 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008812 return;
8813 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008814
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008815 // Mask/mark of zero will not detect anything interesting.
8816 // Don't install rules unless both values are nonzero.
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008817 if (mWakeUpMark == 0 || mWakeUpMask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09008818 return;
8819 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008820
Suprabh Shukla1e312032023-01-24 03:36:37 -08008821 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008822 try {
8823 if (add) {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008824 mNetd.wakeupAddInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008825 } else {
Maciej Żenczykowskicf41fc82023-06-02 07:48:11 +00008826 mNetd.wakeupDelInterface(iface, prefix, mWakeUpMark, mWakeUpMask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09008827 }
8828 } catch (Exception e) {
8829 loge("Exception modifying wakeup packet monitoring: " + e);
8830 }
Joel Scherpelza235a812017-05-22 13:47:41 +09008831 }
8832
Junyu Lai970963e2022-10-25 15:46:47 +08008833 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09008834 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008835 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09008836 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08008837 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09008838 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09008839 for (final String iface : interfaceDiff.added) {
8840 try {
8841 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008842 mRoutingCoordinatorService.addInterfaceToNetwork(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008843 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08008844 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08008845 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09008846 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08008847 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09008848 }
Paul Jensenbff73492014-04-28 10:33:11 -04008849 }
8850 }
Chalard Jean9589e722019-11-19 19:03:53 +09008851 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04008852 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008853 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08008854 wakeupModifyInterface(iface, nai, false);
Chalard Jean2fb66f12023-08-25 12:50:37 +09008855 mRoutingCoordinatorService.removeInterfaceFromNetwork(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04008856 } catch (Exception e) {
8857 loge("Exception removing interface: " + e);
8858 }
8859 }
8860 }
8861
Paul Jensene0fd4a82014-08-06 15:51:33 -04008862 /**
8863 * Have netd update routes from oldLp to newLp.
8864 * @return true if routes changed between oldLp and newLp
8865 */
Junyu Lai970963e2022-10-25 15:46:47 +08008866 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8867 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008868 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008869 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8870 new CompareOrUpdateResult<>(
8871 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008872 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008873 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008874
8875 // add routes before removing old in case it helps with continuous connectivity
8876
Chalard Jean9dd11612018-06-04 16:52:49 +09008877 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008878 for (RouteInfo route : routeDiff.added) {
8879 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008880 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008881 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008882 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008883 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008884 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008885 loge("Exception in addRoute for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008886 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008887 }
8888 }
8889 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008890 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008891 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008892 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008893 mRoutingCoordinatorService.addRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008894 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008895 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008896 loge("Exception in addRoute for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008897 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008898 }
8899 }
8900
8901 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008902 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008903 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008904 mRoutingCoordinatorService.removeRoute(netId, route);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008905 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008906 loge("Exception in removeRoute: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008907 }
8908 }
Tyler Weare4314862019-12-05 14:55:30 -08008909
8910 for (RouteInfo route : routeDiff.updated) {
8911 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8912 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008913 mRoutingCoordinatorService.updateRoute(netId, route);
Tyler Weare4314862019-12-05 14:55:30 -08008914 } catch (Exception e) {
Chalard Jean2fb66f12023-08-25 12:50:37 +09008915 loge("Exception in updateRoute: " + e);
Tyler Weare4314862019-12-05 14:55:30 -08008916 }
8917 }
8918 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8919 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008920 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008921
Junyu Lai970963e2022-10-25 15:46:47 +08008922 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8923 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008924 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8925 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008926 }
Erik Klineb9888902016-04-05 13:30:49 +09008927
Erik Kline31b4a9e2018-01-11 21:07:29 +09008928 if (DBG) {
8929 final Collection<InetAddress> dnses = newLp.getDnsServers();
8930 log("Setting DNS servers for network " + netId + " to " + dnses);
8931 }
Erik Klineb9888902016-04-05 13:30:49 +09008932 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008933 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008934 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008935 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008936 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008937 }
Erik Kline54e35c02017-04-07 15:29:29 +09008938 }
8939
Junyu Lai970963e2022-10-25 15:46:47 +08008940 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8941 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008942 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8943 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008944 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8945 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008946
8947 if (!wasFiltering && !needsFiltering) {
8948 // Nothing to do.
8949 return;
8950 }
8951
8952 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8953 // Nothing changed.
8954 return;
8955 }
8956
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008957 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008958 if (ranges == null || ranges.isEmpty()) {
8959 return;
8960 }
8961
Qingxi Libb8da982020-01-17 17:54:27 -08008962 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008963 // TODO: this create a window of opportunity for apps to receive traffic between the time
8964 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008965 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008966 // old rules are being removed.
8967 if (wasFiltering) {
8968 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8969 }
8970 if (needsFiltering) {
8971 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8972 }
8973 }
8974
Valentin Iftime9fa35092019-09-24 13:32:13 +02008975 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008976 if (mWolSupportedInterfaces == null) {
8977 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008978 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008979 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008980 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8981 }
8982
Luke Huangb913c812018-08-24 20:33:16 +08008983 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008984 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008985 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008986 }
8987 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008988 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008989 }
Luke Huangb913c812018-08-24 20:33:16 +08008990 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008991 }
8992
Chalard Jean62edfd82019-12-02 18:39:29 +09008993 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8994 @NonNull final NetworkCapabilities newNc) {
8995 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8996 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008997 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008998 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008999 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08009000 } catch (RemoteException | ServiceSpecificException e) {
9001 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09009002 }
9003 }
9004 }
9005
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009006 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009007 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09009008 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009009 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08009010 underlyingNetworks = underlyingNetworksOrDefault(
9011 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09009012 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009013 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
9014 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009015 // metered if any underlying is metered, or originally declared metered by the agent.
9016 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009017 boolean roaming = false; // roaming if any underlying is roaming
9018 boolean congested = false; // congested if any underlying is congested
9019 boolean suspended = true; // suspended if all underlying are suspended
9020
9021 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08009022 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009023 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08009024 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009025 for (Network underlyingNetwork : underlyingNetworks) {
9026 final NetworkAgentInfo underlying =
9027 getNetworkAgentInfoForNetwork(underlyingNetwork);
9028 if (underlying == null) continue;
9029
9030 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
9031 hadUnderlyingNetworks = true;
9032 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09009033 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009034 }
9035
9036 // Merge capabilities of this underlying network. For bandwidth, assume the
9037 // worst case.
9038 downKbps = NetworkCapabilities.minBandwidth(downKbps,
9039 underlyingCaps.getLinkDownstreamBandwidthKbps());
9040 upKbps = NetworkCapabilities.minBandwidth(upKbps,
9041 underlyingCaps.getLinkUpstreamBandwidthKbps());
9042 // If this underlying network is metered, the VPN is metered (it may cost money
9043 // to send packets on this network).
9044 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
9045 // If this underlying network is roaming, the VPN is roaming (the billing structure
9046 // is different than the usual, local one).
9047 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9048 // If this underlying network is congested, the VPN is congested (the current
9049 // condition of the network affects the performance of this network).
9050 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
9051 // If this network is not suspended, the VPN is not suspended (the VPN
9052 // is able to transfer some data).
9053 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08009054 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009055 }
9056 }
9057 if (!hadUnderlyingNetworks) {
9058 // No idea what the underlying networks are; assume reasonable defaults
9059 metered = true;
9060 roaming = false;
9061 congested = false;
9062 suspended = false;
9063 }
9064
Chalard Jean1d420b32022-10-12 16:39:37 +09009065 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009066 newNc.setLinkDownstreamBandwidthKbps(downKbps);
9067 newNc.setLinkUpstreamBandwidthKbps(upKbps);
9068 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
9069 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
9070 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
9071 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08009072 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09009073 }
9074
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009075 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009076 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
9077 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
9078 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04009079 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09009080 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009081 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09009082 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09009083 // Don't complain for VPNs since they're not driven by requests and there is no risk of
9084 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09009085 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09009086 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09009087 if (nai.everConnected()
9088 && !nai.isVPN()
9089 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009090 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09009091 // does not cause any request (that is not a listen) currently matching that agent to
9092 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009093 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09009094 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009095 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09009096 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009097 }
9098
Paul Jensen53f08952015-06-16 14:27:36 -04009099 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009100 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09009101 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009102 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04009103 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009104 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04009105 }
Chalard Jean254bd162022-08-25 13:04:51 +09009106 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009107 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009108 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009109 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04009110 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009111 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009112 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009113 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009114 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009115 }
Chalard Jean254bd162022-08-25 13:04:51 +09009116 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08009117 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9118 } else {
9119 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
9120 }
lucasline117e2e2019-10-22 18:27:33 +08009121 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009122
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009123 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09009124 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
9125 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009126 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09009127 }
9128
Lorenzo Colittibd079452021-07-02 11:47:57 +09009129 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09009130 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09009131 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009132 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09009133 }
9134
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009135 return newNc;
9136 }
9137
Lorenzo Colitti44840702021-01-11 22:27:57 +09009138 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
9139 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
9140 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9141 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9142 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9143 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
9144 if (prevSuspended != suspended) {
9145 // TODO (b/73132094) : remove this call once the few users of onSuspended and
9146 // onResumed have been removed.
9147 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
9148 : ConnectivityManager.CALLBACK_RESUMED);
9149 }
9150 if (prevSuspended != suspended || prevRoaming != roaming) {
9151 // updateNetworkInfo will mix in the suspended info from the capabilities and
9152 // take appropriate action for the network having possibly changed state.
9153 updateNetworkInfo(nai, nai.networkInfo);
9154 }
9155 }
9156
Ying Xu7cabd322024-01-15 18:40:15 -08009157 private void handleUidCarrierPrivilegesLost(int uid) {
9158 ensureRunningOnConnectivityServiceThread();
9159 // A NetworkRequest needs to be revoked when all the conditions are met
9160 // 1. It requests restricted network
9161 // 2. The requestor uid matches the uid with the callback
9162 // 3. The app doesn't have Carrier Privileges
9163 // 4. The app doesn't have permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS
9164 for (final NetworkRequest nr : mNetworkRequests.keySet()) {
9165 if ((nr.isRequest() || nr.isListen())
9166 && !nr.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
9167 && nr.getRequestorUid() == uid
9168 && !hasConnectivityRestrictedNetworksPermission(uid, true)) {
9169 declareNetworkRequestUnfulfillable(nr);
9170 }
9171 }
9172
9173 // A NetworkAgent's allowedUids may need to be updated if the app has lost
9174 // carrier config
9175 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
9176 if (nai.networkCapabilities.getAllowedUidsNoCopy().contains(uid)) {
9177 final NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
9178 NetworkAgentInfo.restrictCapabilitiesFromNetworkAgent(
9179 nc,
9180 uid,
9181 false /* hasAutomotiveFeature (irrelevant) */,
9182 mDeps,
9183 mCarrierPrivilegeAuthenticator);
9184 updateCapabilities(nai.getScore(), nai, nc);
9185 }
9186 }
9187 }
9188
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009189 /**
9190 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
9191 *
9192 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
9193 * capabilities we manage and store in {@code nai}, such as validated status and captive
9194 * portal status)
9195 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
9196 * potentially triggers rematches.
9197 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
9198 * change.)
9199 *
9200 * @param oldScore score of the network before any of the changes that prompted us
9201 * to call this function.
9202 * @param nai the network having its capabilities updated.
9203 * @param nc the new network capabilities.
9204 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009205 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09009206 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009207 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09009208 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09009209 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
9210 if (null != differences) {
9211 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
9212 }
Chalard Jean62edfd82019-12-02 18:39:29 +09009213 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09009214 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009215
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009216 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09009217 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09009218 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009219
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009220 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009221 // If the requestable capabilities haven't changed, and the score hasn't changed, then
9222 // the change we're processing can't affect any requests, it can only affect the listens
9223 // on this network. We might have been called by rematchNetworkAndRequests when a
9224 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09009225 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009226 } else {
9227 // If the requestable capabilities have changed or the score changed, we can't have been
9228 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009229 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04009230 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009231 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09009232 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06009233
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009234 final boolean oldMetered = prevNc.isMetered();
9235 final boolean newMetered = newNc.isMetered();
9236 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08009237
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009238 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00009239 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
9240 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009241 }
junyulaif2c67e42018-08-07 19:50:45 +08009242
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009243 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
9244 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08009245
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009246 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08009247 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09009248 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06009249 }
9250
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009251 // This network might have been underlying another network. Propagate its capabilities.
9252 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08009253
Ken Chen5a35cf92023-10-07 07:54:22 +08009254 if (meteredChanged || !newNc.equalsTransportTypes(prevNc)) {
Ken Chen6b134f12023-10-07 07:46:47 +08009255 mDnsManager.updateCapabilitiesForNetwork(nai.network.getNetId(), newNc);
chenbruce7b2f8982020-02-20 14:28:31 +08009256 }
lucaslin53e8a262021-06-08 01:43:59 +08009257
9258 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009259 }
9260
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009261 /** Convenience method to update the capabilities for a given network. */
9262 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09009263 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009264 }
9265
Yang Sun29037f62023-12-04 10:31:58 +08009266 private void maybeApplyMulticastRoutingConfig(@NonNull final NetworkAgentInfo nai,
9267 final LocalNetworkConfig oldConfig,
9268 final LocalNetworkConfig newConfig) {
9269 final MulticastRoutingConfig oldUpstreamConfig =
9270 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9271 oldConfig.getUpstreamMulticastRoutingConfig();
9272 final MulticastRoutingConfig oldDownstreamConfig =
9273 oldConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9274 oldConfig.getDownstreamMulticastRoutingConfig();
9275 final MulticastRoutingConfig newUpstreamConfig =
9276 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9277 newConfig.getUpstreamMulticastRoutingConfig();
9278 final MulticastRoutingConfig newDownstreamConfig =
9279 newConfig == null ? MulticastRoutingConfig.CONFIG_FORWARD_NONE :
9280 newConfig.getDownstreamMulticastRoutingConfig();
9281
9282 if (oldUpstreamConfig.equals(newUpstreamConfig) &&
9283 oldDownstreamConfig.equals(newDownstreamConfig)) {
9284 return;
9285 }
9286
9287 final String downstreamNetworkName = nai.linkProperties.getInterfaceName();
9288 final LocalNetworkInfo lni = localNetworkInfoForNai(nai);
9289 final Network upstreamNetwork = lni.getUpstreamNetwork();
9290
9291 if (upstreamNetwork != null) {
9292 final String upstreamNetworkName =
9293 getLinkProperties(upstreamNetwork).getInterfaceName();
9294 applyMulticastRoutingConfig(downstreamNetworkName, upstreamNetworkName, newConfig);
9295 }
9296 }
9297
9298 private void applyMulticastRoutingConfig(@NonNull String localNetworkInterfaceName,
9299 @NonNull String upstreamNetworkInterfaceName,
9300 @NonNull final LocalNetworkConfig config) {
Yang Sunca537d52024-01-19 12:53:50 +08009301 if (mMulticastRoutingCoordinatorService == null) {
9302 if (config.getDownstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE ||
9303 config.getUpstreamMulticastRoutingConfig().getForwardingMode() != FORWARD_NONE) {
9304 loge("Multicast routing is not supported, failed to configure " + config
9305 + " for " + localNetworkInterfaceName + " to "
9306 + upstreamNetworkInterfaceName);
9307 }
9308 return;
9309 }
Yang Sun29037f62023-12-04 10:31:58 +08009310
9311 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9312 upstreamNetworkInterfaceName, config.getUpstreamMulticastRoutingConfig());
9313 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9314 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9315 config.getDownstreamMulticastRoutingConfig());
9316 }
9317
9318 private void disableMulticastRouting(@NonNull String localNetworkInterfaceName,
9319 @NonNull String upstreamNetworkInterfaceName) {
Yang Sunca537d52024-01-19 12:53:50 +08009320 if (mMulticastRoutingCoordinatorService == null) {
9321 return;
9322 }
Yang Sun29037f62023-12-04 10:31:58 +08009323
9324 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig(localNetworkInterfaceName,
9325 upstreamNetworkInterfaceName, MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9326 mMulticastRoutingCoordinatorService.applyMulticastRoutingConfig
9327 (upstreamNetworkInterfaceName, localNetworkInterfaceName,
9328 MulticastRoutingConfig.CONFIG_FORWARD_NONE);
9329 }
9330
Chalard Jean1e4c2182023-10-06 18:45:53 +09009331 // oldConfig is null iff this is the original registration of the local network config
Chalard Jean22350c92023-10-07 19:21:45 +09009332 private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
Chalard Jean1e4c2182023-10-06 18:45:53 +09009333 @Nullable final LocalNetworkConfig oldConfig,
9334 @NonNull final LocalNetworkConfig newConfig) {
9335 if (!nai.isLocalNetwork()) {
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009336 Log.wtf(TAG, "Ignoring update of a local network info on non-local network " + nai);
9337 return;
9338 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009339
Chalard Jean4fe23392023-10-17 23:02:27 +09009340 if (VDBG) {
9341 Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
9342 }
Chalard Jean1e4c2182023-10-06 18:45:53 +09009343 final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
Chalard Jean1e4c2182023-10-06 18:45:53 +09009344 configBuilder.setUpstreamMulticastRoutingConfig(
9345 newConfig.getUpstreamMulticastRoutingConfig());
9346 configBuilder.setDownstreamMulticastRoutingConfig(
9347 newConfig.getDownstreamMulticastRoutingConfig());
9348
9349 final NetworkRequest oldRequest =
9350 (null == oldConfig) ? null : oldConfig.getUpstreamSelector();
9351 final NetworkCapabilities oldCaps =
9352 (null == oldRequest) ? null : oldRequest.networkCapabilities;
9353 final NetworkRequestInfo oldNri =
9354 null == oldRequest ? null : mNetworkRequests.get(oldRequest);
9355 final NetworkAgentInfo oldSatisfier =
9356 null == oldNri ? null : oldNri.getSatisfier();
9357 final NetworkRequest newRequest = newConfig.getUpstreamSelector();
9358 final NetworkCapabilities newCaps =
9359 (null == newRequest) ? null : newRequest.networkCapabilities;
9360 final boolean requestUpdated = !Objects.equals(newCaps, oldCaps);
9361 if (null != oldRequest && requestUpdated) {
9362 handleRemoveNetworkRequest(mNetworkRequests.get(oldRequest));
9363 if (null == newRequest && null != oldSatisfier) {
9364 // If there is an old satisfier, but no new request, then remove the old upstream.
9365 removeLocalNetworkUpstream(nai, oldSatisfier);
9366 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009367 // When there is a new request, the rematch sees the new request and sends the
9368 // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
9369 // But here there is no new request, so the rematch won't see anything. Send
9370 // callbacks to apps now to tell them about the loss of upstream.
9371 notifyNetworkCallbacks(nai,
9372 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +09009373 return;
9374 }
9375 }
9376 if (null != newRequest && requestUpdated) {
9377 // File the new request if :
9378 // - it has changed (requestUpdated), or
9379 // - it's the first time this local info (null == oldConfig)
9380 // is updated and the request has not been filed yet.
9381 // Requests for local info are always LISTEN_FOR_BEST, because they have at most one
9382 // upstream (the best) but never request it to be brought up.
9383 final NetworkRequest nr = new NetworkRequest(newCaps, ConnectivityManager.TYPE_NONE,
9384 nextNetworkRequestId(), LISTEN_FOR_BEST);
9385 configBuilder.setUpstreamSelector(nr);
9386 final NetworkRequestInfo nri = new NetworkRequestInfo(
9387 nai.creatorUid, nr, null /* messenger */, null /* binder */,
9388 0 /* callbackFlags */, null /* attributionTag */);
9389 if (null != oldSatisfier) {
9390 // Set the old satisfier in the new NRI so that the rematch will see any changes
9391 nri.setSatisfier(oldSatisfier, nr);
9392 }
9393 nai.localNetworkConfig = configBuilder.build();
Chalard Jean22350c92023-10-07 19:21:45 +09009394 // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
9395 // nai.localNetworkConfig is set, since it will base its callbacks on the old
9396 // satisfier and the new request.
Chalard Jean1e4c2182023-10-06 18:45:53 +09009397 handleRegisterNetworkRequest(nri);
9398 } else {
9399 configBuilder.setUpstreamSelector(oldRequest);
9400 nai.localNetworkConfig = configBuilder.build();
9401 }
Yang Sun29037f62023-12-04 10:31:58 +08009402 maybeApplyMulticastRoutingConfig(nai, oldConfig, newConfig);
Chalard Jeanf9d0e3e2023-10-17 13:23:17 +09009403 }
9404
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009405 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00009406 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009407 *
9408 * Ingress interface filtering enforces that all apps under the given network can only receive
9409 * packets from the network's interface (and loopback). This is important for VPNs because
9410 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
9411 * non-VPN interfaces.
9412 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00009413 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009414 * 1. the network is an app VPN (not legacy VPN)
9415 * 2. the VPN does not allow bypass
9416 * 3. the VPN is fully-routed
9417 * 4. the VPN interface is non-null
9418 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09009419 * @see INetd#firewallAddUidInterfaceRules
9420 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009421 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00009422 @Nullable
9423 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009424 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009425 if (nc == null || lp == null) return null;
9426 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009427 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08009428 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009429 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08009430 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00009431 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00009432 && !lp.hasExcludeRoute()) {
9433 return lp.getInterfaceName();
9434 }
9435 return null;
9436 }
9437
9438 /**
9439 * Returns whether we need to set interface filtering rule or not
9440 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00009441 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00009442 String isolationIface) {
9443 // Allow rules are always needed if VPN isolation is enabled.
9444 if (isolationIface != null) return true;
9445
9446 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
9447 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
9448 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
Chalard Jeandf29a852023-05-29 17:02:43 +09009449 return mDeps.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009450 }
9451
Chiachang Wang28afaff2020-12-10 22:24:47 +08009452 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
9453 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
9454 int index = 0;
9455 for (UidRange range : ranges) {
9456 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
9457 index++;
9458 }
9459 return stableRanges;
9460 }
9461
Chalard Jeane6c95272022-01-25 21:04:21 +09009462 private static UidRangeParcel[] intsToUidRangeStableParcels(
9463 final @NonNull ArraySet<Integer> uids) {
9464 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
9465 int index = 0;
9466 for (int uid : uids) {
9467 stableRanges[index] = new UidRangeParcel(uid, uid);
9468 index++;
9469 }
9470 return stableRanges;
9471 }
9472
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009473 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
9474 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
9475 for (int i = 0; i < ranges.length; i++) {
9476 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
9477 }
9478 return stableRanges;
9479 }
9480
Motomu Utsumi93a22182023-03-16 17:04:21 +09009481 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
Motomu Utsumi1d137262023-06-04 21:32:08 +09009482 UidRangeParcel[] uidRangeParcels, int[] exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08009483 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
9484 try {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009485 if (mDeps.isAtLeastU()) {
9486 final Set<Integer> exemptUidSet = new ArraySet<>();
9487 for (final int uid: exemptUids) {
9488 exemptUidSet.add(uid);
9489 }
9490 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUidSet);
9491 } else {
9492 mNetd.socketDestroy(uidRangeParcels, exemptUids);
9493 }
Ken Chen5e65a852020-12-24 12:59:10 +08009494 } catch (Exception e) {
9495 loge("Exception in socket destroy: ", e);
9496 }
9497 }
9498 }
9499
paulhuaa0743d2021-05-26 21:56:03 +08009500 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi1d137262023-06-04 21:32:08 +09009501 int[] exemptUids = new int[2];
Ken Chen5e65a852020-12-24 12:59:10 +08009502 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
9503 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
9504 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi1d137262023-06-04 21:32:08 +09009505 exemptUids[0] = VPN_UID;
9506 exemptUids[1] = nai.networkCapabilities.getOwnerUid();
Ken Chen5e65a852020-12-24 12:59:10 +08009507 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
9508
Motomu Utsumi6345e462023-03-13 13:24:50 +09009509 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009510 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009511 try {
9512 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08009513 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009514 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009515 } else {
paulhu0e79d952021-06-09 16:11:35 +08009516 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08009517 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08009518 }
9519 } catch (Exception e) {
9520 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
9521 " on netId " + nai.network.netId + ". " + e);
9522 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09009523 // Close sockets that established connection while requesting netd.
Motomu Utsumi1d137262023-06-04 21:32:08 +09009524 maybeCloseSockets(nai, uidRanges, ranges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08009525 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009526
lucaslin53e8a262021-06-08 01:43:59 +08009527 private boolean isProxySetOnAnyDefaultNetwork() {
9528 ensureRunningOnConnectivityServiceThread();
9529 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9530 final NetworkAgentInfo nai = nri.getSatisfier();
9531 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
9532 return true;
9533 }
9534 }
9535 return false;
9536 }
9537
9538 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
9539 NetworkCapabilities newNc) {
9540 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
9541 // the proxy might be changed since the default network satisfied by the apps might also
9542 // changed.
9543 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
9544 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09009545 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
9546 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09009547 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08009548 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
9549 mProxyTracker.sendProxyBroadcast();
9550 }
9551 }
9552
Chalard Jeane6c95272022-01-25 21:04:21 +09009553 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
9554 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00009555 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
9556 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09009557 if (null == prevRanges) prevRanges = new ArraySet<>();
9558 if (null == newRanges) newRanges = new ArraySet<>();
9559 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
9560
9561 prevRanges.removeAll(newRanges);
9562 newRanges.removeAll(prevRangesCopy);
9563
9564 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009565 // When updating the VPN uid routing rules, add the new range first then remove the old
9566 // range. If old range were removed first, there would be a window between the old
9567 // range being removed and the new range being added, during which UIDs contained
9568 // in both ranges are not subject to any VPN routing rules. Adding new range before
9569 // removing old range works because, unlike the filtering rules below, it's possible to
9570 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08009571 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
9572 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
9573 // [1-5] & [1-2],[4-5] == [3]
9574 // Then we can do:
9575 // maybeCloseSockets([3])
9576 // mNetd.networkAddUidRanges([1-2],[4-5])
9577 // mNetd.networkRemoveUidRanges([1-5])
9578 // maybeCloseSockets([3])
9579 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
9580 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09009581 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009582 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009583 }
9584 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08009585 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009586 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00009587 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
9588 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00009589 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
9590 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009591 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09009592 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009593 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
9594 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
9595 // were added first and then newRanges got removed later, there would be only one uid
9596 // 10013 left. A consequence of removing old ranges before adding new ranges is that
9597 // there is now a window of opportunity when the UIDs are not subject to any filtering.
9598 // Note that this is in contrast with the (more robust) update of VPN routing rules
9599 // above, where the addition of new ranges happens before the removal of old ranges.
9600 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
9601 // to be removed will never overlap with the new range to be added.
9602 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009603 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
9604 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009605 }
9606 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00009607 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00009608 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09009609 } catch (Exception e) {
9610 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009611 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09009612 }
9613 }
9614
Chalard Jeande665262022-02-25 16:12:12 +09009615 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09009616 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
9617 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09009618 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
9619 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09009620 if (prevEmpty && newEmpty) return;
9621
9622 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09009623 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009624 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09009625 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09009626
9627 if (prevUids.equals(newUids)) return;
9628
9629 // This implementation is very simple and vastly faster for sets of Integers than
9630 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
9631 // a key computed from the value and has storage for that.
9632 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
9633 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
9634 toRemove.removeAll(newUids);
9635 toAdd.removeAll(prevUids);
Chalard Jeane6c95272022-01-25 21:04:21 +09009636 try {
9637 if (!toAdd.isEmpty()) {
9638 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
9639 nai.network.netId,
9640 intsToUidRangeStableParcels(toAdd),
9641 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9642 }
9643 if (!toRemove.isEmpty()) {
9644 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
9645 nai.network.netId,
9646 intsToUidRangeStableParcels(toRemove),
9647 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
9648 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009649 } catch (ServiceSpecificException e) {
9650 // Has the interface disappeared since the network was built ?
9651 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09009652 } catch (RemoteException e) {
9653 // Netd died. This usually causes a runtime restart anyway.
9654 }
9655 }
9656
Junyu Lai2ed7d412022-10-07 16:52:21 +08009657 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
9658 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09009659 ensureRunningOnConnectivityServiceThread();
9660
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09009661 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00009662 // Ignore updates for disconnected networks
9663 return;
9664 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009665 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009666 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09009667 + "; created=" + nai.getCreatedTime()
9668 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00009669 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09009670 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
9671 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08009672 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00009673 }
9674
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009675 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
9676 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009677 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009678 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08009679 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08009680 // If apps could file multi-layer requests with PendingIntents, they'd need to know
9681 // which of the layer is satisfied alongside with some ID for the request. Hence, if
9682 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09009683 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
9684 // need to be sent as a separate extra.
9685 final NetworkRequest req = nri.isMultilayerRequest()
9686 ? nri.getActiveRequest()
9687 // Non-multilayer listen requests do not have an active request
9688 : nri.mRequests.get(0);
9689 if (req == null) {
9690 Log.wtf(TAG, "No request in NRI " + nri);
9691 }
9692 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009693 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009694 sendIntent(nri.mPendingIntent, intent);
9695 }
9696 // else not handled
9697 }
9698
Michael Groover73f69482023-01-27 11:01:25 -06009699 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
9700 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009701 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
9702 mPendingIntentWakeLock.acquire();
9703 try {
9704 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00009705 final BroadcastOptions options = BroadcastOptions.makeBasic();
Chalard Jeandf29a852023-05-29 17:02:43 +09009706 if (mDeps.isAtLeastT()) {
chiachangwanga36518c2022-05-26 05:19:41 +00009707 // Explicitly disallow the receiver from starting activities, to prevent apps from
9708 // utilizing the PendingIntent as a backdoor to do this.
9709 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
9710 }
9711 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
9712 null /* requiredPermission */,
Chalard Jeandf29a852023-05-29 17:02:43 +09009713 mDeps.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009714 } catch (PendingIntent.CanceledException e) {
9715 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
9716 mPendingIntentWakeLock.release();
9717 releasePendingNetworkRequest(pendingIntent);
9718 }
9719 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
9720 }
9721
9722 @Override
9723 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
9724 String resultData, Bundle resultExtras) {
9725 if (DBG) log("Finished sending " + pendingIntent);
9726 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08009727 // Release with a delay so the receiving client has an opportunity to put in its
9728 // own request.
9729 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009730 }
9731
Chalard Jean22350c92023-10-07 19:21:45 +09009732 @Nullable
9733 private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
9734 if (!nai.isLocalNetwork()) return null;
9735 final Network upstream;
9736 final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
9737 if (null == selector) {
9738 upstream = null;
9739 } else {
9740 final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
9741 final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
9742 upstream = (null == satisfier) ? null : satisfier.network;
9743 }
9744 return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
9745 }
9746
Chalard Jean46bfbf02022-02-02 00:56:25 +09009747 // networkAgent is only allowed to be null if notificationType is
9748 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
9749 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08009750 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09009751 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08009752 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08009753 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08009754 // Default request has no msgr. Also prevents callbacks from being invoked for
9755 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
9756 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
9757 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009758 }
Chalard Jeane0aaca52023-10-17 13:23:07 +09009759 final Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08009760 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009761 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08009762 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08009763 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009764 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009765 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
9766 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009767 }
Roshan Pius951c0032020-12-22 15:10:42 -08009768 final boolean includeLocationSensitiveInfo =
9769 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009770 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009771 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08009772 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08009773 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09009774 networkCapabilitiesRestrictedForCallerPermissions(
9775 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
9776 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009777 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09009778 nri.mCallingAttributionTag);
9779 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009780 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9781 networkAgent.linkProperties, nri.mPid, nri.mUid));
Chalard Jean22350c92023-10-07 19:21:45 +09009782 // The local network info is often null, so can't use the static putParcelable
9783 // method here.
9784 bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
9785 localNetworkInfoForNai(networkAgent));
junyulaif2c67e42018-08-07 19:50:45 +08009786 // For this notification, arg1 contains the blocked status.
9787 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09009788 break;
9789 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009790 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009791 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009792 break;
9793 }
9794 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09009795 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08009796 final NetworkCapabilities netCap =
9797 networkCapabilitiesRestrictedForCallerPermissions(
9798 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
9799 putParcelable(
9800 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08009801 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08009802 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08009803 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08009804 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009805 break;
9806 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009807 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09009808 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
9809 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009810 break;
9811 }
junyulaif2c67e42018-08-07 19:50:45 +08009812 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09009813 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08009814 msg.arg1 = arg1;
9815 break;
9816 }
Chalard Jean22350c92023-10-07 19:21:45 +09009817 case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
9818 if (!networkAgent.isLocalNetwork()) {
9819 Log.wtf(TAG, "Callback for local info for a non-local network");
9820 return;
9821 }
9822 putParcelable(bundle, localNetworkInfoForNai(networkAgent));
9823 break;
9824 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009825 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009826 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07009827 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009828 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009829 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009830 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08009831 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07009832 }
James Mattis45d81842021-01-10 14:24:24 -08009833 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009834 } catch (RemoteException e) {
9835 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08009836 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009837 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009838 }
9839
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09009840 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
9841 bundle.putParcelable(t.getClass().getSimpleName(), t);
9842 }
9843
Chalard Jean0702f982021-09-16 21:50:07 +09009844 /**
9845 * Returns whether reassigning a request from an NAI to another can be done gracefully.
9846 *
9847 * When a request should be assigned to a new network, it is normally lingered to give
9848 * time for apps to gracefully migrate their connections. When both networks are on the same
9849 * radio, but that radio can't do time-sharing efficiently, this may end up being
9850 * counter-productive because any traffic on the old network may drastically reduce the
9851 * performance of the new network.
9852 * The stack supports a configuration to let modem vendors state that their radio can't
9853 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
9854 * from one cell network to another can't be done gracefully.
9855 *
9856 * @param oldNai the old network serving the request
9857 * @param newNai the new network serving the request
9858 * @return whether the switch can be graceful
9859 */
9860 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
9861 @NonNull final NetworkAgentInfo newSatisfier) {
9862 if (mCellularRadioTimesharingCapable) return true;
9863 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9864 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
9865 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
9866 }
9867
Paul Jensenaf94b982014-09-30 15:37:41 -04009868 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009869 if (nai.numRequestNetworkRequests() != 0) {
9870 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9871 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09009872 // Ignore listening and track default requests.
9873 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009874 loge("Dead network still had at least " + nr);
9875 break;
9876 }
Paul Jensenaf94b982014-09-30 15:37:41 -04009877 }
Jean Chalard3160bc02023-06-27 08:54:23 +00009878 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04009879 }
9880
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009881 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
9882 if (oldNetwork == null) {
9883 loge("Unknown NetworkAgentInfo in handleLingerComplete");
9884 return;
9885 }
Chalard Jean49707572019-12-10 21:07:02 +09009886 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009887
9888 // If we get here it means that the last linger timeout for this network expired. So there
9889 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08009890 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009891
Lorenzo Colitti2666be82016-09-09 18:48:56 +09009892 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009893 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009894 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009895 } else {
junyulai0ac374f2020-12-14 18:41:52 +08009896 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09009897 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009898 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009899 }
9900
James Mattise3ef1912020-12-20 11:09:58 -08009901 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
9902 boolean isDefaultChanged = false;
9903 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
9904 final NetworkReassignment.RequestReassignment reassignment =
9905 changes.getReassignment(defaultRequestInfo);
9906 if (null == reassignment) {
9907 continue;
9908 }
9909 // reassignment only contains those instances where the satisfying network changed.
9910 isDefaultChanged = true;
9911 // Notify system services of the new default.
9912 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
9913 }
Chiachang Wang087fd272018-09-28 22:42:48 +08009914
James Mattise3ef1912020-12-20 11:09:58 -08009915 if (isDefaultChanged) {
9916 // Hold a wakelock for a short time to help apps in migrating to a new default.
9917 scheduleReleaseNetworkTransitionWakelock();
9918 }
9919 }
9920
Aaron Huang9fe47be2021-06-08 13:11:45 +08009921 private void resetHttpProxyForNonDefaultNetwork(NetworkAgentInfo oldDefaultNetwork) {
9922 if (null == oldDefaultNetwork) return;
9923 // The network stopped being the default. If it was using a PAC proxy, then the
9924 // proxy needs to be reset, otherwise HTTP requests on this network may be sent
9925 // to the local proxy server, which would forward them over the newly default network.
9926 final ProxyInfo proxyInfo = oldDefaultNetwork.linkProperties.getHttpProxy();
9927 if (null == proxyInfo || !proxyInfo.isPacProxy()) return;
9928 oldDefaultNetwork.linkProperties.setHttpProxy(new ProxyInfo(proxyInfo.getPacFileUrl()));
9929 notifyNetworkCallbacks(oldDefaultNetwork, CALLBACK_IP_CHANGED);
9930 }
9931
James Mattise3ef1912020-12-20 11:09:58 -08009932 private void makeDefault(@NonNull final NetworkRequestInfo nri,
9933 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9934 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9935 if (DBG) {
9936 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
9937 }
Chalard Jean8e382112019-12-03 20:45:30 +09009938
James Mattisd31bdfa2020-12-23 16:37:26 -08009939 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
9940 if (newDefaultNetwork != null) {
9941 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04009942 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09009943
James Mattisd31bdfa2020-12-23 16:37:26 -08009944 // Set an app level managed default and return since further processing only applies to the
9945 // default network.
9946 if (mDefaultRequest != nri) {
9947 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
9948 return;
9949 }
9950
9951 makeDefaultNetwork(newDefaultNetwork);
9952
James Mattise3ef1912020-12-20 11:09:58 -08009953 if (oldDefaultNetwork != null) {
9954 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
9955 }
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +09009956 mNetworkActivityTracker.updateDefaultNetwork(newDefaultNetwork, oldDefaultNetwork);
Motomu Utsumi188bfd32023-05-30 14:38:04 +09009957 maybeClosePendingFrozenSockets(newDefaultNetwork, oldDefaultNetwork);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009958 mProxyTracker.setDefaultProxy(null != newDefaultNetwork
James Mattise3ef1912020-12-20 11:09:58 -08009959 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
Aaron Huang9fe47be2021-06-08 13:11:45 +08009960 resetHttpProxyForNonDefaultNetwork(oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08009961 updateTcpBufferSizes(null != newDefaultNetwork
9962 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09009963 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04009964 }
9965
James Mattisd31bdfa2020-12-23 16:37:26 -08009966 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
9967 @Nullable final NetworkAgentInfo oldDefaultNetwork,
9968 @Nullable final NetworkAgentInfo newDefaultNetwork) {
9969 try {
9970 if (VDBG) {
9971 log("Setting default network for " + nri
9972 + " using UIDs " + nri.getUids()
9973 + " with old network " + (oldDefaultNetwork != null
9974 ? oldDefaultNetwork.network().getNetId() : "null")
9975 + " and new network " + (newDefaultNetwork != null
9976 ? newDefaultNetwork.network().getNetId() : "null"));
9977 }
9978 if (nri.getUids().isEmpty()) {
9979 throw new IllegalStateException("makeDefaultForApps called without specifying"
9980 + " any applications to set as the default." + nri);
9981 }
9982 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009983 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009984 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009985 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009986 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009987 }
9988 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08009989 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08009990 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08009991 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08009992 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08009993 }
9994 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09009995 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08009996 }
9997 }
9998
Junyu Lai35665cc2022-12-19 17:37:48 +08009999 /**
10000 * Collect restricted uid ranges for the given network and UserHandle, these uids
10001 * are not restricted for matched enterprise networks but being restricted for non-matched
10002 * enterprise networks and non-enterprise networks.
10003 */
10004 @NonNull
10005 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
10006 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
10007 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
10008 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
10009 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
10010
10011 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
10012 // The NC is built from a `ProfileNetworkPreference` which has only one
10013 // enterprise ID, so it's guaranteed to have exactly one.
10014 final int prefId = pref.capabilities.getEnterpriseIds()[0];
10015 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
10016 continue;
10017 }
10018 }
10019
10020 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
10021 pref.capabilities.getUidRanges())) {
10022 throw new IllegalArgumentException(
10023 "Overlapping uid range in preference: " + pref);
10024 }
10025 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
10026 }
10027 return restrictedUidRanges;
10028 }
10029
10030 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +080010031 // Netd command is not implemented before U.
Chalard Jeandf29a852023-05-29 17:02:43 +090010032 if (!mDeps.isAtLeastU()) return;
Junyu Laic53a1692023-02-20 15:36:54 +080010033
Junyu Lai35665cc2022-12-19 17:37:48 +080010034 ensureRunningOnConnectivityServiceThread();
10035 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
10036 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
10037 .getUserHandles(true /* excludeDying */);
10038 if (users.isEmpty()) {
10039 throw new IllegalStateException("No user is available");
10040 }
10041
10042 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10043 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
10044 for (final UserHandle user : users) {
10045 final ArraySet<UidRange> restrictedUidRanges =
10046 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
10047 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
10048 UidRange.createForUser(user), restrictedUidRanges));
10049 }
10050
10051 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
10052 configs.add(new NativeUidRangeConfig(
10053 nai.network.netId, rangesParcel, 0 /* subPriority */));
10054 }
10055
10056 // The netd API replaces the previous configs with the current configs.
10057 // Thus, for network disconnection or preference removal, no need to
10058 // unset previous config. Instead, collecting all currently needed
10059 // configs and issue to netd.
10060 try {
10061 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
10062 } catch (ServiceSpecificException e) {
10063 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +080010064 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +080010065 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +080010066 // Netd died. This will cause a runtime restart anyway.
10067 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +080010068 }
10069 }
10070
James Mattisd31bdfa2020-12-23 16:37:26 -080010071 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
10072 try {
10073 if (null != newDefaultNetwork) {
10074 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
10075 } else {
10076 mNetd.networkClearDefault();
10077 }
10078 } catch (RemoteException | ServiceSpecificException e) {
10079 loge("Exception setting default network :" + e);
10080 }
10081 }
10082
Chalard Jean05cbe972019-12-09 11:50:38 +090010083 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010084 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +090010085 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +090010086 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +090010087 processNewlySatisfiedListenRequests(nai);
10088 }
10089
10090 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -080010091 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10092 if (nri.isMultilayerRequest()) {
10093 continue;
10094 }
10095 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010096 if (!nr.isListen()) continue;
10097 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -080010098 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010099 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
10100 }
10101 }
Chalard Jeancd397a22019-11-22 22:33:33 +090010102 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010103
Chalard Jeancd397a22019-11-22 22:33:33 +090010104 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -080010105 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10106 if (nri.isMultilayerRequest()) {
10107 continue;
10108 }
10109 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010110 if (!nr.isListen()) continue;
10111 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
10112 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +090010113 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +090010114 }
10115 }
10116 }
10117
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010118 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010119 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010120 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -080010121 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +090010122 @Nullable public final NetworkRequest mOldNetworkRequest;
10123 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010124 @Nullable public final NetworkAgentInfo mOldNetwork;
10125 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -080010126 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010127 @Nullable final NetworkRequest oldNetworkRequest,
10128 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010129 @Nullable final NetworkAgentInfo oldNetwork,
10130 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010131 mNetworkRequestInfo = networkRequestInfo;
10132 mOldNetworkRequest = oldNetworkRequest;
10133 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010134 mOldNetwork = oldNetwork;
10135 mNewNetwork = newNetwork;
10136 }
Chalard Jean49707572019-12-10 21:07:02 +090010137
10138 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +090010139 final NetworkRequest requestToShow = null != mNewNetworkRequest
10140 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
10141 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -080010142 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
10143 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +090010144 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010145 }
10146
Chalard Jean46a62372019-12-10 21:25:24 +090010147 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010148
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010149 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +090010150 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010151 }
10152
10153 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +090010154 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +090010155 // The code is never supposed to add two reassignments of the same request. Make
10156 // sure this stays true, but without imposing this expensive check on all
10157 // reassignments on all user devices.
10158 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -080010159 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +090010160 throw new IllegalStateException("Trying to reassign ["
10161 + reassignment + "] but already have ["
10162 + existing + "]");
10163 }
10164 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +090010165 }
Chalard Jean46a62372019-12-10 21:25:24 +090010166 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010167 }
10168
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010169 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +090010170 // the passed request.
10171 @Nullable
10172 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010173 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010174 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +090010175 }
10176 return null;
10177 }
Chalard Jean49707572019-12-10 21:07:02 +090010178
10179 public String toString() {
10180 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
10181 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +090010182 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010183 for (final RequestReassignment rr : getRequestReassignments()) {
10184 sj.add(rr.toString());
10185 }
10186 return sj.toString();
10187 }
10188
10189 public String debugString() {
10190 final StringBuilder sb = new StringBuilder();
10191 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +090010192 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +090010193 for (final RequestReassignment rr : getRequestReassignments()) {
10194 sb.append("\n ").append(rr);
10195 }
10196 return sb.append("\n").toString();
10197 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +090010198 }
10199
Chalard Jean24344d72019-12-04 13:32:31 +090010200 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +090010201 @Nullable final NetworkRequest previousRequest,
10202 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +090010203 @Nullable final NetworkAgentInfo previousSatisfier,
10204 @Nullable final NetworkAgentInfo newSatisfier,
10205 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -080010206 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +090010207 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +090010208 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010209 if (VDBG || DDBG) {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010210 log(" accepting network in place of " + previousSatisfier.toShortString()
10211 + " for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010212 }
James Mattisa076c532020-12-02 14:12:41 -080010213 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010214 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +090010215 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +090010216 // If this network switch can't be supported gracefully, the request is not
10217 // lingered. This allows letting go of the network sooner to reclaim some
10218 // performance on the new network, since the radio can't do both at the same
10219 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +090010220 //
10221 // Also don't linger the request if the old network has been destroyed.
10222 // A destroyed network does not provide actual network connectivity, so
10223 // lingering it is not useful. In particular this ensures that a destroyed
10224 // network is outscored by its replacement,
10225 // then it is torn down immediately instead of being lingered, and any apps that
10226 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +090010227 previousSatisfier.lingerRequest(previousRequest.requestId, now);
10228 }
Chalard Jean24344d72019-12-04 13:32:31 +090010229 } else {
Chalard Jean1e4c2182023-10-06 18:45:53 +090010230 if (VDBG || DDBG) log(" accepting network in place of null for " + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010231 }
junyulai0ac374f2020-12-14 18:41:52 +080010232
10233 // To prevent constantly CPU wake up for nascent timer, if a network comes up
10234 // and immediately satisfies a request then remove the timer. This will happen for
10235 // all networks except in the case of an underlying network for a VCN.
10236 if (newSatisfier.isNascent()) {
10237 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +080010238 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010239 }
10240
Chalard Jean5d6e23b2021-03-01 22:00:20 +090010241 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -080010242 newSatisfier.unlingerRequest(newRequest.requestId);
10243 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +080010244 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -080010245 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010246 }
Chalard Jeana8ac2302021-03-01 22:16:08 +090010247 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +090010248 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010249 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -080010250 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010251 }
James Mattisa076c532020-12-02 14:12:41 -080010252 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +090010253 }
James Mattisa076c532020-12-02 14:12:41 -080010254 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +090010255 }
10256
James Mattisa076c532020-12-02 14:12:41 -080010257 /**
10258 * This function is triggered when something can affect what network should satisfy what
10259 * request, and it computes the network reassignment from the passed collection of requests to
10260 * network match to the one that the system should now have. That data is encoded in an
10261 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
10262 * satisfier.
10263 *
10264 * After the reassignment is computed, it is applied to the state objects.
10265 *
10266 * @param networkRequests the nri objects to evaluate for possible network reassignment
10267 * @return NetworkReassignment listing of proposed network assignment changes
10268 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010269 @NonNull
James Mattisa076c532020-12-02 14:12:41 -080010270 private NetworkReassignment computeNetworkReassignment(
10271 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +090010272 final NetworkReassignment changes = new NetworkReassignment();
10273
Chalard Jeanc81d4c32021-04-07 17:06:19 +090010274 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +090010275 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010276 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +090010277 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +090010278 }
Chalard Jean857a1712019-12-10 21:08:07 +090010279
James Mattisa076c532020-12-02 14:12:41 -080010280 for (final NetworkRequestInfo nri : networkRequests) {
10281 // Non-multilayer listen requests can be ignored.
10282 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
10283 continue;
10284 }
10285 NetworkAgentInfo bestNetwork = null;
10286 NetworkRequest bestRequest = null;
10287 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +090010288 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -080010289 // Stop evaluating as the highest possible priority request is satisfied.
10290 if (null != bestNetwork) {
10291 bestRequest = req;
10292 break;
10293 }
10294 }
James Mattisd31bdfa2020-12-23 16:37:26 -080010295 if (null == bestNetwork && isDefaultBlocked(nri)) {
10296 // Remove default networking if disallowed for managed default requests.
10297 bestNetwork = mNoServiceNetwork;
10298 }
10299 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +090010300 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +090010301 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -080010302 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +090010303 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010304 }
10305 return changes;
10306 }
10307
James Mattisa076c532020-12-02 14:12:41 -080010308 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
10309 return new HashSet<>(mNetworkRequests.values());
10310 }
10311
Paul Jensenc88b39b2015-06-16 14:27:36 -040010312 /**
James Mattisa076c532020-12-02 14:12:41 -080010313 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -040010314 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -040010315 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010316 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -080010317 rematchNetworksAndRequests(getNrisFromGlobalRequests());
10318 }
10319
10320 /**
10321 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
10322 * being disconnected.
10323 */
10324 private void rematchNetworksAndRequests(
10325 @NonNull final Set<NetworkRequestInfo> networkRequests) {
10326 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +090010327 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +090010328 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -080010329 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +090010330 final long computed = SystemClock.elapsedRealtime();
10331 applyNetworkReassignment(changes, start);
10332 final long applied = SystemClock.elapsedRealtime();
10333 issueNetworkNeeds();
10334 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +090010335 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010336 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
10337 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010338 log(changes.debugString());
10339 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +090010340 // Shorter form, only one line of log
10341 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
10342 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +090010343 }
Chalard Jeand7f762d2019-12-10 19:01:29 +090010344 }
Chalard Jean64520dc2019-12-04 19:55:32 +090010345
Chalard Jean1e4c2182023-10-06 18:45:53 +090010346 private boolean hasSameInterfaceName(@Nullable final NetworkAgentInfo nai1,
10347 @Nullable final NetworkAgentInfo nai2) {
10348 if (null == nai1) return null == nai2;
10349 if (null == nai2) return false;
10350 return nai1.linkProperties.getInterfaceName()
10351 .equals(nai2.linkProperties.getInterfaceName());
10352 }
10353
Chalard Jeand7f762d2019-12-10 19:01:29 +090010354 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +090010355 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010356 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +090010357
10358 // Since most of the time there are only 0 or 1 background networks, it would probably
10359 // be more efficient to just use an ArrayList here. TODO : measure performance
10360 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
10361 for (final NetworkAgentInfo nai : nais) {
10362 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
10363 }
10364
Chalard Jeand7f762d2019-12-10 19:01:29 +090010365 // First, update the lists of satisfied requests in the network agents. This is necessary
10366 // because some code later depends on this state to be correct, most prominently computing
10367 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +090010368 for (final NetworkReassignment.RequestReassignment event :
10369 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -080010370 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
10371 event.mOldNetworkRequest, event.mNewNetworkRequest,
10372 event.mOldNetwork, event.mNewNetwork,
10373 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +090010374 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010375
James Mattise3ef1912020-12-20 11:09:58 -080010376 // Process default network changes if applicable.
10377 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010378
Chalard Jean68eab722023-11-16 17:00:04 +090010379 // Update forwarding rules for the upstreams of local networks. Do this before sending
10380 // onAvailable so that by the time onAvailable is sent the forwarding rules are set up.
10381 // Don't send CALLBACK_LOCAL_NETWORK_INFO_CHANGED yet though : they should be sent after
10382 // onAvailable so clients know what network the change is about. Store such changes in
10383 // an array that's only allocated if necessary (because it's almost never necessary).
10384 ArrayList<NetworkAgentInfo> localInfoChangedAgents = null;
10385 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
10386 if (!nai.isLocalNetwork()) continue;
10387 final NetworkRequest nr = nai.localNetworkConfig.getUpstreamSelector();
10388 if (null == nr) continue; // No upstream for this local network
10389 final NetworkRequestInfo nri = mNetworkRequests.get(nr);
10390 final NetworkReassignment.RequestReassignment change = changes.getReassignment(nri);
10391 if (null == change) continue; // No change in upstreams for this network
10392 final String fromIface = nai.linkProperties.getInterfaceName();
10393 if (!hasSameInterfaceName(change.mOldNetwork, change.mNewNetwork)
10394 || change.mOldNetwork.isDestroyed()) {
10395 // There can be a change with the same interface name if the new network is the
10396 // replacement for the old network that was unregisteredAfterReplacement.
10397 try {
10398 if (null != change.mOldNetwork) {
10399 mRoutingCoordinatorService.removeInterfaceForward(fromIface,
10400 change.mOldNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010401 disableMulticastRouting(fromIface,
10402 change.mOldNetwork.linkProperties.getInterfaceName());
Chalard Jean68eab722023-11-16 17:00:04 +090010403 }
10404 // If the new upstream is already destroyed, there is no point in setting up
10405 // a forward (in fact, it might forward to the interface for some new network !)
10406 // Later when the upstream disconnects CS will try to remove the forward, which
10407 // is ignored with a benign log by RoutingCoordinatorService.
10408 if (null != change.mNewNetwork && !change.mNewNetwork.isDestroyed()) {
10409 mRoutingCoordinatorService.addInterfaceForward(fromIface,
10410 change.mNewNetwork.linkProperties.getInterfaceName());
Yang Sun29037f62023-12-04 10:31:58 +080010411 applyMulticastRoutingConfig(fromIface,
10412 change.mNewNetwork.linkProperties.getInterfaceName(),
10413 nai.localNetworkConfig);
Chalard Jean68eab722023-11-16 17:00:04 +090010414 }
10415 } catch (final RemoteException e) {
10416 loge("Can't update forwarding rules", e);
10417 }
10418 }
10419 if (null == localInfoChangedAgents) localInfoChangedAgents = new ArrayList<>();
10420 localInfoChangedAgents.add(nai);
10421 }
10422
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010423 // Notify requested networks are available after the default net is switched, but
10424 // before LegacyTypeTracker sends legacy broadcasts
10425 for (final NetworkReassignment.RequestReassignment event :
10426 changes.getRequestReassignments()) {
10427 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -080010428 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010429 } else {
James Mattisa076c532020-12-02 14:12:41 -080010430 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +090010431 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +090010432 }
10433 }
10434
junyulai0ac374f2020-12-14 18:41:52 +080010435 // Update the inactivity state before processing listen callbacks, because the background
10436 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010437 // just yet though, because they have to be sent after the listens are processed to keep
10438 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +080010439 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +090010440 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +080010441 // Rematching may have altered the inactivity state of some networks, so update all
10442 // inactivity timers. updateInactivityState reads the state from the network agent
10443 // and does nothing if the state has not changed : the source of truth is controlled
10444 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
10445 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +080010446 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +080010447 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010448 }
10449 }
10450
Chalard Jeanb10ab412019-12-11 14:12:30 +090010451 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010452 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010453 // Process listen requests and update capabilities if the background state has
10454 // changed for this network. For consistency with previous behavior, send onLost
10455 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +090010456 processNewlyLostListenRequests(nai);
10457 if (oldBackground != nai.isBackgroundNetwork()) {
10458 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010459 }
Chalard Jeanb10ab412019-12-11 14:12:30 +090010460 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +090010461 }
10462
junyulai0ac374f2020-12-14 18:41:52 +080010463 for (final NetworkAgentInfo nai : inactiveNetworks) {
10464 // For nascent networks, if connecting with no foreground request, skip broadcasting
10465 // LOSING for backward compatibility. This is typical when mobile data connected while
10466 // wifi connected with mobile data always-on enabled.
10467 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010468 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010469 }
10470
Chalard Jean68eab722023-11-16 17:00:04 +090010471 // Send LOCAL_NETWORK_INFO_CHANGED callbacks now that onAvailable and onLost have been sent.
10472 if (null != localInfoChangedAgents) {
10473 for (final NetworkAgentInfo nai : localInfoChangedAgents) {
10474 notifyNetworkCallbacks(nai,
10475 ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
Chalard Jean1e4c2182023-10-06 18:45:53 +090010476 }
10477 }
10478
James Mattise3ef1912020-12-20 11:09:58 -080010479 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +090010480
Chalard Jeanf01b2ef2019-11-07 23:16:12 +090010481 // Tear down all unneeded networks.
Jean Chalard3160bc02023-06-27 08:54:23 +000010482 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010483 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +080010484 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +090010485 // This network has active linger timers and no requests, but is not
10486 // lingering. Linger it.
10487 //
10488 // One way (the only way?) this can happen if this network is unvalidated
10489 // and became unneeded due to another network improving its score to the
10490 // point where this network will no longer be able to satisfy any requests
10491 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +080010492 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010493 notifyNetworkLosing(nai, now);
10494 }
Chalard Jean0a8afda2019-11-07 19:05:18 +090010495 } else {
Chalard Jean49707572019-12-10 21:07:02 +090010496 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +090010497 teardownUnneededNetwork(nai);
10498 }
10499 }
Paul Jensen05e85ee2014-09-11 11:00:39 -040010500 }
10501 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010502
Chalard Jean62edfd82019-12-02 18:39:29 +090010503 /**
10504 * Apply a change in background state resulting from rematching networks with requests.
10505 *
10506 * During rematch, a network may change background states by starting to satisfy or stopping
10507 * to satisfy a foreground request. Listens don't count for this. When a network changes
10508 * background states, its capabilities need to be updated and callbacks fired for the
10509 * capability change.
10510 *
10511 * @param nai The network that changed background states
10512 */
10513 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
10514 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
10515 if (Objects.equals(nai.networkCapabilities, newNc)) return;
10516 updateNetworkPermissions(nai, newNc);
10517 nai.getAndSetNetworkCapabilities(newNc);
10518 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
10519 }
10520
Chalard Jeanf0344532019-11-19 19:23:38 +090010521 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -080010522 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +090010523 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +090010524 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
10525 changes.getReassignment(mDefaultRequest);
10526 final NetworkAgentInfo oldDefaultNetwork =
10527 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
10528 final NetworkAgentInfo newDefaultNetwork =
10529 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -080010530
Chalard Jean5b409c72021-02-04 13:12:59 +090010531 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010532 // Maintain the illusion : since the legacy API only understands one network at a time,
10533 // if the default network changed, apps should see a disconnected broadcast for the
10534 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +090010535 if (oldDefaultNetwork != null) {
10536 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
10537 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010538 }
Chalard Jean5b409c72021-02-04 13:12:59 +090010539 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +090010540 // The new default network can be newly null if and only if the old default
10541 // network doesn't satisfy the default request any more because it lost a
10542 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +090010543 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -080010544 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +090010545 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +090010546 }
10547 }
10548
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010549 // Now that all the callbacks have been sent, send the legacy network broadcasts
10550 // as needed. This is necessary so that legacy requests correctly bind dns
10551 // requests to this network. The legacy users are listening for this broadcast
10552 // and will generally do a dns request so they can ensureRouteToHost and if
10553 // they do that before the callbacks happen they'll use the default network.
10554 //
10555 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
10556 // callbacks, but if apps can receive the broadcast before the callback, they still might
10557 // have an inconsistent view of networking.
10558 //
10559 // This *does* introduce a race where if the user uses the new api
10560 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
10561 // they may get old info. Reverse this after the old startUsing api is removed.
10562 // This is on top of the multiple intent sequencing referenced in the todo above.
10563 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +090010564 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +090010565 addNetworkToLegacyTypeTracker(nai);
10566 }
The Android Open Source Project28527d22009-03-03 19:31:44 -080010567 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010568 }
10569
Chalard Jean0354d8c2021-01-12 10:58:56 +090010570 private void issueNetworkNeeds() {
10571 ensureRunningOnConnectivityServiceThread();
10572 for (final NetworkOfferInfo noi : mNetworkOffers) {
10573 issueNetworkNeeds(noi);
10574 }
10575 }
10576
10577 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
10578 ensureRunningOnConnectivityServiceThread();
10579 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
10580 informOffer(nri, noi.offer, mNetworkRanker);
10581 }
10582 }
10583
10584 /**
10585 * Inform a NetworkOffer about any new situation of a request.
10586 *
10587 * This function handles updates to offers. A number of events may happen that require
10588 * updating the registrant for this offer about the situation :
10589 * • The offer itself was updated. This may lead the offer to no longer being able
10590 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
10591 * or conversely being strengthened enough to beat the satisfier (and therefore
10592 * start being needed)
10593 * • The network satisfying a request changed (including cases where the request
10594 * starts or stops being satisfied). The new network may be a stronger or weaker
10595 * match than the old one, possibly affecting whether the offer is needed.
10596 * • The network satisfying a request updated their score. This may lead the offer
10597 * to no longer be able to beat it if the current satisfier got better, or
10598 * conversely start being a good choice if the current satisfier got weaker.
10599 *
10600 * @param nri The request
10601 * @param offer The offer. This may be an updated offer.
10602 */
10603 private static void informOffer(@NonNull NetworkRequestInfo nri,
10604 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
10605 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
10606 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +090010607
10608 // Multi-layer requests have a currently active request, the one being satisfied.
10609 // Since the system will try to bring up a better network than is currently satisfying
10610 // the request, NetworkProviders need to be told the offers matching the requests *above*
10611 // the currently satisfied one are needed, that the ones *below* the satisfied one are
10612 // not needed, and the offer is needed for the active request iff the offer can beat
10613 // the satisfier.
10614 // For non-multilayer requests, the logic above gracefully degenerates to only the
10615 // last case.
10616 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
10617 // providers that the offer is needed for this request, until the active request is found.
10618 // In a second phase, deal with the currently active request. In a third phase, inform
10619 // the providers that offer is unneeded for the remaining requests.
10620
10621 // First phase : inform providers of all requests above the active request.
10622 int i;
10623 for (i = 0; nri.mRequests.size() > i; ++i) {
10624 final NetworkRequest request = nri.mRequests.get(i);
10625 if (activeRequest == request) break; // Found the active request : go to phase 2
10626 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10627 // Since this request is higher-priority than the one currently satisfied, if the
10628 // offer can satisfy it, the provider should try and bring up the network for sure ;
10629 // no need to even ask the ranker – an offer that can satisfy is always better than
10630 // no network. Hence tell the provider so unless it already knew.
10631 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
10632 offer.onNetworkNeeded(request);
10633 }
10634 }
10635
10636 // Second phase : deal with the active request (if any)
10637 if (null != activeRequest && activeRequest.isRequest()) {
10638 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +000010639 // If an offer can satisfy the request, it is considered needed if it is currently
10640 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +090010641 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +000010642 && satisfier.factorySerialNumber == offer.providerId
10643 && activeRequest.canBeSatisfiedBy(offer.caps);
10644 final boolean newNeeded = currentlyServing
10645 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +090010646 if (newNeeded != oldNeeded) {
10647 if (newNeeded) {
10648 offer.onNetworkNeeded(activeRequest);
10649 } else {
10650 // The offer used to be able to beat the satisfier. Now it can't.
10651 offer.onNetworkUnneeded(activeRequest);
10652 }
10653 }
10654 }
10655
10656 // Third phase : inform the providers that the offer isn't needed for any request
10657 // below the active one.
10658 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
10659 final NetworkRequest request = nri.mRequests.get(i);
10660 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
10661 // Since this request is lower-priority than the one currently satisfied, if the
10662 // offer can satisfy it, the provider should not try and bring up the network.
10663 // Hence tell the provider so unless it already knew.
10664 if (offer.neededFor(request)) {
10665 offer.onNetworkUnneeded(request);
10666 }
10667 }
10668 }
10669
Chalard Jean61c79252019-11-07 23:07:32 +090010670 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
10671 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10672 NetworkRequest nr = nai.requestAt(i);
10673 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
10674 // legacy type tracker filters out repeat adds
10675 mLegacyTypeTracker.add(nr.legacyType, nai);
10676 }
10677 }
10678
10679 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +090010680 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +090010681 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
10682 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
10683 if (nai.isVPN()) {
10684 mLegacyTypeTracker.add(TYPE_VPN, nai);
10685 }
10686 }
10687
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +090010688 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -040010689 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +090010690 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +090010691 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -040010692 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +090010693 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010694
Chalard Jean254bd162022-08-25 13:04:51 +090010695 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -040010696 // Don't repeat publish.
10697 if (newInetCondition == mDefaultInetConditionPublished) return;
10698
10699 mDefaultInetConditionPublished = newInetCondition;
10700 sendInetConditionBroadcast(nai.networkInfo);
10701 }
10702
Chalard Jeand61375d2020-01-14 22:46:36 +090010703 @NonNull
10704 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
10705 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010706 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +090010707 final boolean suspended =
10708 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
10709 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
10710 // Only override the state with SUSPENDED if the network is currently in CONNECTED
10711 // state. This is because the network could have been suspended before connecting,
10712 // or it could be disconnecting while being suspended, and in both these cases
10713 // the state should not be overridden. Note that the only detailed state that
10714 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
10715 // worry about multiple different substates of CONNECTED.
10716 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
10717 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010718 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
10719 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
10720 // network agent is created, then goes to suspended, then goes out of suspended without
10721 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +090010722 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +080010723 ? NetworkInfo.DetailedState.CONNECTED
10724 : NetworkInfo.DetailedState.CONNECTING,
10725 info.getReason(),
10726 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +090010727 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +090010728 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +090010729 return newInfo;
10730 }
10731
10732 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
10733 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
10734
Erik Kline99f301b2017-02-15 19:59:17 +090010735 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -070010736 NetworkInfo oldInfo = null;
10737 synchronized (networkAgent) {
10738 oldInfo = networkAgent.networkInfo;
10739 networkAgent.networkInfo = newInfo;
10740 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010741
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010742 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +090010743 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
10744 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010745 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070010746
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010747 if (shouldCreateNativeNetwork(networkAgent, state)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +090010748 // A network that has just connected has zero requests and is thus a foreground network.
10749 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
10750
Luke Huangfdd11f82019-04-09 18:41:49 +080010751 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010752
10753 networkAgent.setCreated();
10754
10755 // If the network is created immediately on register, then apply the LinkProperties now.
10756 // Otherwise, this is done further down when the network goes into connected state.
10757 // Applying the LinkProperties means that the network is ready to carry traffic -
10758 // interfaces and routing rules have been added, DNS servers programmed, etc.
10759 // For VPNs, this must be done before the capabilities are updated, because as soon as
10760 // that happens, UIDs are routed to the network.
10761 if (shouldCreateNetworksImmediately()) {
10762 applyInitialLinkProperties(networkAgent);
10763 }
10764
10765 // TODO: should this move earlier? It doesn't seem to have anything to do with whether
10766 // a network is created or not.
Lorenzo Colittibd079452021-07-02 11:47:57 +090010767 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +090010768 // Initialize the network's capabilities to their starting values according to the
10769 // underlying networks. This ensures that the capabilities are correct before
10770 // anything happens to the network.
10771 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +090010772 }
Chiachang Wang3f6cc072021-03-24 18:39:17 +080010773 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +090010774 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +080010775 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010776 }
10777
Chalard Jean254bd162022-08-25 13:04:51 +090010778 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
10779 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +010010780
lucaslin45e639b2019-04-03 17:09:28 +080010781 // NetworkCapabilities need to be set before sending the private DNS config to
10782 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +090010783 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
10784
Erik Kline9a62f012018-03-21 07:18:33 -070010785 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
Lorenzo Colitti4f87aa32022-07-25 13:20:37 +090010786 if (!shouldCreateNetworksImmediately()) {
10787 applyInitialLinkProperties(networkAgent);
10788 } else {
10789 // The network was created when the agent registered, and the LinkProperties are
10790 // already up-to-date. However, updateLinkProperties also makes some changes only
10791 // when the network connects. Apply those changes here. On T and below these are
10792 // handled by the applyInitialLinkProperties call just above.
10793 // TODO: stop relying on updateLinkProperties(..., null) to do this.
10794 // If something depends on both LinkProperties and connected state, it should be in
10795 // this method as well.
10796 networkAgent.clatd.update();
10797 updateProxy(networkAgent.linkProperties, null);
10798 }
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010799
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010800 // If a rate limit has been configured and is applicable to this network (network
10801 // provides internet connectivity), apply it. The tc police filter cannot be attached
10802 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
Chalard Jean2fb66f12023-08-25 12:50:37 +090010803 // updateInterfaces -> RoutingCoordinatorManager#addInterfaceToNetwork
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +010010804 // Note: in case of a system server crash, the NetworkController constructor in netd
10805 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
10806 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
10807 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
10808 mIngressRateLimit);
10809 }
10810
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010811 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
10812 // command must be sent after updating LinkProperties to maximize chances of
10813 // NetworkMonitor seeing the correct LinkProperties when starting.
10814 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +090010815 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +090010816 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +090010817 }
Chalard Jeand4900722022-02-06 12:25:38 +090010818 final NetworkMonitorParameters params = new NetworkMonitorParameters();
10819 params.networkAgentConfig = networkAgent.networkAgentConfig;
10820 params.networkCapabilities = networkAgent.networkCapabilities;
10821 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
10822 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010823 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
10824 // newer callback even before T. However getInterfaceVersion is a synchronized binder
10825 // call that would cause a Log.wtf to be emitted from the system_server process, and
10826 // in the absence of a satisfactory, scalable solution which follows an easy/standard
10827 // process to check the interface version, just use an SDK check. NetworkStack will
10828 // always be new enough when running on T+.
Chalard Jeandf29a852023-05-29 17:02:43 +090010829 if (mDeps.isAtLeastT()) {
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +090010830 networkAgent.networkMonitor().notifyNetworkConnected(params);
10831 } else {
10832 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
10833 params.networkCapabilities);
10834 }
Chalard Jean0f141332023-06-05 19:26:17 +090010835 final long evaluationDelay;
10836 if (!networkAgent.networkCapabilities.hasSingleTransport(TRANSPORT_WIFI)) {
10837 // If the network is anything other than pure wifi, use the default timeout.
10838 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10839 } else if (networkAgent.networkAgentConfig.isExplicitlySelected()) {
10840 // If the network is explicitly selected, use the default timeout because it's
10841 // shorter and the user is likely staring at the screen expecting it to validate
10842 // right away.
10843 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10844 } else if (avoidBadWifi() || !activelyPreferBadWifi()) {
10845 // If avoiding bad wifi, or if not avoiding but also not preferring bad wifi
10846 evaluationDelay = DEFAULT_EVALUATION_TIMEOUT_MS;
10847 } else {
10848 // It's wifi, automatically connected, and bad wifi is preferred : use the
10849 // longer timeout to avoid the device switching to captive portals with bad
10850 // signal or very slow response.
10851 evaluationDelay = ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
10852 }
10853 scheduleEvaluationTimeout(networkAgent.network, evaluationDelay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010854
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010855 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
10856 // be communicated to a particular NetworkAgent depends only on the network's immutable,
10857 // capabilities, so it only needs to be done once on initial connect, not every time the
10858 // network's capabilities change. Note that we do this before rematching the network,
10859 // so we could decide to tear it down immediately afterwards. That's fine though - on
10860 // disconnection NetworkAgents should stop any signal strength monitoring they have been
10861 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +090010862 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +090010863
junyulai0ac374f2020-12-14 18:41:52 +080010864 // Before first rematching networks, put an inactivity timer without any request, this
10865 // allows {@code updateInactivityState} to update the state accordingly and prevent
10866 // tearing down for any {@code unneeded} evaluation in this period.
10867 // Note that the timer will not be rescheduled since the expiry time is
10868 // fixed after connection regardless of the network satisfying other requests or not.
10869 // But it will be removed as soon as the network satisfies a request for the first time.
10870 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
10871 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +080010872 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +080010873
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090010874 if (mTrackMultiNetworkActivities) {
10875 // Start tracking activity of this network.
10876 // This must be called before rematchAllNetworksAndRequests since the network
10877 // should be tracked when the network becomes the default network.
10878 // This method does not trigger any callbacks or broadcasts. Callbacks or broadcasts
10879 // can be triggered later if this network becomes the default network.
10880 mNetworkActivityTracker.setupDataActivityTracking(networkAgent);
10881 }
10882
Paul Jensen05e85ee2014-09-11 11:00:39 -040010883 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010884 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +090010885
10886 // This has to happen after matching the requests, because callbacks are just requests.
10887 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010888 } else if (state == NetworkInfo.State.DISCONNECTED) {
Jean Chalard3160bc02023-06-27 08:54:23 +000010889 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -040010890 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +000010891 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -040010892 }
Chalard Jeand9fffc32018-05-11 20:19:20 +090010893 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +000010894 if (networkAgent.isVPN()) {
10895 // As the active or bound network changes for apps, broadcast the default proxy, as
10896 // apps may need to update their proxy data. This is called after disconnecting from
10897 // VPN to make sure we do not broadcast the old proxy data.
10898 // TODO(b/122649188): send the broadcast only to VPN users.
10899 mProxyTracker.sendProxyBroadcast();
10900 }
Chalard Jean254bd162022-08-25 13:04:51 +090010901 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
10902 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070010903 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -070010904 }
10905 }
10906
Chalard Jean28018572020-12-21 18:36:52 +090010907 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +090010908 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
10909 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +090010910 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -070010911 }
10912
Erik Kline99f301b2017-02-15 19:59:17 +090010913 // Notify only this one new request of the current state. Transfer all the
10914 // current state by calling NetworkCapabilities and LinkProperties callbacks
10915 // so that callers can be guaranteed to have as close to atomicity in state
10916 // transfer as can be supported by this current API.
10917 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -070010918 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +090010919 if (nri.mPendingIntent != null) {
10920 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
10921 // Attempt no subsequent state pushes where intents are involved.
10922 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -080010923 }
Erik Kline99f301b2017-02-15 19:59:17 +090010924
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010925 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +080010926 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010927 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
10928 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
10929 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +080010930 }
10931
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010932 // Notify the requests on this NAI that the network is now lingered.
10933 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +080010934 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +090010935 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
10936 }
10937
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010938 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
10939 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
10940 return vpnBlocked
10941 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
10942 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
10943 }
10944
10945 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
10946 if (blockedReasons == BLOCKED_REASON_NONE) {
10947 mUidBlockedReasons.delete(uid);
10948 } else {
10949 mUidBlockedReasons.put(uid, blockedReasons);
10950 }
10951 }
10952
junyulaif2c67e42018-08-07 19:50:45 +080010953 /**
10954 * Notify of the blocked state apps with a registered callback matching a given NAI.
10955 *
10956 * Unlike other callbacks, blocked status is different between each individual uid. So for
10957 * any given nai, all requests need to be considered according to the uid who filed it.
10958 *
10959 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010960 * @param oldMetered True if the previous network capabilities were metered.
10961 * @param newMetered True if the current network capabilities are metered.
10962 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
10963 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +080010964 */
10965 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +000010966 boolean newMetered, List<UidRange> oldBlockedUidRanges,
10967 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +080010968
10969 for (int i = 0; i < nai.numNetworkRequests(); i++) {
10970 NetworkRequest nr = nai.requestAt(i);
10971 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010972
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010973 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
10974 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
10975 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010976 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010977 : oldVpnBlocked;
10978
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010979 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
10980 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
10981 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +080010982 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010983 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080010984 }
10985 }
10986 }
10987
10988 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +000010989 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +080010990 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +000010991 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +080010992 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010993 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090010994 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +080010995 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +090010996 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +000010997
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090010998 final int oldBlockedState = getBlockedState(
10999 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
11000 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
11001 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +080011002 continue;
junyulaif2c67e42018-08-07 19:50:45 +080011003 }
junyulaif2c67e42018-08-07 19:50:45 +080011004 for (int i = 0; i < nai.numNetworkRequests(); i++) {
11005 NetworkRequest nr = nai.requestAt(i);
11006 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011007 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090011008 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
11009 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +080011010 }
11011 }
11012 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011013 }
11014
Chalard Jean3a3f5f22019-04-10 23:07:55 +090011015 @VisibleForTesting
11016 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +090011017 // The NetworkInfo we actually send out has no bearing on the real
11018 // state of affairs. For example, if the default connection is mobile,
11019 // and a request for HIPRI has just gone away, we need to pretend that
11020 // HIPRI has just disconnected. So we need to set the type to HIPRI and
11021 // the state to DISCONNECTED, even though the network is of type MOBILE
11022 // and is still connected.
11023 NetworkInfo info = new NetworkInfo(nai.networkInfo);
11024 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +090011025 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070011026 if (state != DetailedState.DISCONNECTED) {
11027 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +090011028 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011029 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -070011030 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -070011031 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
11032 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
11033 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
11034 if (info.isFailover()) {
11035 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
11036 nai.networkInfo.setFailover(false);
11037 }
11038 if (info.getReason() != null) {
11039 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
11040 }
11041 if (info.getExtraInfo() != null) {
11042 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
11043 }
11044 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +090011045 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -080011046 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -070011047 if (newDefaultAgent != null) {
11048 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
11049 newDefaultAgent.networkInfo);
11050 } else {
11051 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
11052 }
11053 }
11054 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
11055 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +090011056 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011057 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +090011058 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -070011059 }
11060 }
11061 }
11062
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011063 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +090011064 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +090011065 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +090011066 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +090011067 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +090011068 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
11069 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -070011070 NetworkRequestInfo nri = mNetworkRequests.get(nr);
11071 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011072 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011073 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -080011074 } else {
11075 sendPendingIntentForRequest(nri, networkAgent, notifyType);
11076 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011077 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -070011078 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -070011079
Lorenzo Colitti79869ea2016-07-01 01:53:25 +090011080 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
11081 notifyNetworkCallbacks(networkAgent, notifyType, 0);
11082 }
11083
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011084 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +090011085 * Returns the list of all interfaces that could be used by network traffic that does not
11086 * explicitly specify a network. This includes the default network, but also all VPNs that are
11087 * currently connected.
11088 *
11089 * Must be called on the handler thread.
11090 */
junyulaie7c7d2a2021-01-26 15:29:15 +080011091 @NonNull
11092 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080011093 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -080011094 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -080011095 final Set<Integer> activeNetIds = new ArraySet<>();
11096 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
11097 if (nri.isBeingSatisfied()) {
11098 activeNetIds.add(nri.getSatisfier().network().netId);
11099 }
11100 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +090011101 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +090011102 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +090011103 defaultNetworks.add(nai.network);
11104 }
11105 }
junyulaie7c7d2a2021-01-26 15:29:15 +080011106 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +090011107 }
11108
11109 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +090011110 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
11111 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011112 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -080011113 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -080011114 ensureRunningOnConnectivityServiceThread();
11115 String activeIface = null;
11116 LinkProperties activeLinkProperties = getActiveLinkProperties();
11117 if (activeLinkProperties != null) {
11118 activeIface = activeLinkProperties.getInterfaceName();
11119 }
Benedict Wong9308cd32019-06-12 17:46:31 +000011120
junyulai2050bed2021-01-23 09:46:34 +080011121 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011122 try {
junyulaide41fc22021-01-22 22:46:01 +080011123 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +090011124 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +080011125 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
11126 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -080011127 } catch (Exception ignored) {
11128 }
11129 }
11130
Sreeram Ramachandrane4586322014-07-27 14:18:26 -070011131 @Override
Udam Sainicd645462016-01-04 12:16:14 -080011132 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +080011133 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +090011134 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +090011135 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011136
11137 if (!TextUtils.isEmpty(settingUrl)) {
11138 return settingUrl;
11139 }
11140
11141 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080011142 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +010011143 if (!TextUtils.isEmpty(settingUrl)) {
11144 return settingUrl;
11145 }
11146
11147 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -080011148 }
11149
11150 @Override
junyulai070f9ff2019-01-16 20:23:34 +080011151 public void startNattKeepalive(Network network, int intervalSeconds,
11152 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011153 enforceKeepalivePermission();
11154 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +080011155 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +000011156 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
11157 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +000011158 // false and set the underpinned network to null because there is no way and no
11159 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
11160 // deprecated method.
11161 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011162 }
11163
11164 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011165 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080011166 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000011167 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070011168 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080011169 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011170 mKeepaliveTracker.startNattKeepalive(
11171 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000011172 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
11173 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070011174 } finally {
11175 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11176 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011177 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11178 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011179 }
11180 }
junyulaid05a1922019-01-15 11:32:44 +080011181 }
11182
11183 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080011184 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080011185 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070011186 try {
11187 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080011188 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070011189 mKeepaliveTracker.startTcpKeepalive(
11190 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
11191 } finally {
11192 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
11193 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080011194 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
11195 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070011196 }
11197 }
junyulai0835a1e2019-01-08 20:04:33 +080011198 }
11199
11200 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011201 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011202 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090011203 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
11204 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090011205 }
11206
11207 @Override
Remi NGUYEN VANbee2ee12023-02-20 20:10:09 +090011208 public int[] getSupportedKeepalives() {
11209 enforceAnyPermissionOf(mContext, android.Manifest.permission.NETWORK_SETTINGS,
11210 // Backwards compatibility with CTS 13
11211 android.Manifest.permission.QUERY_ALL_PACKAGES);
11212
11213 return BinderUtils.withCleanCallingIdentity(() ->
11214 KeepaliveResourceUtil.getSupportedKeepalives(mContext));
11215 }
11216
11217 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070011218 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080011219 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070011220
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011221 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080011222 final long token = Binder.clearCallingIdentity();
11223 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011224 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
11225 UserHandle.getUserHandleForUid(uid))) {
11226 return;
11227 }
11228
Heemin Seogdb8489d2019-06-12 09:21:44 -070011229 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
11230 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080011231
11232 // Turn airplane mode off
11233 setAirplaneMode(false);
11234
11235 // restore private DNS settings to default mode (opportunistic)
11236 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
11237 UserHandle.getUserHandleForUid(uid))) {
11238 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
11239 PRIVATE_DNS_MODE_OPPORTUNISTIC);
11240 }
11241
11242 Settings.Global.putString(mContext.getContentResolver(),
11243 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080011244 } finally {
11245 Binder.restoreCallingIdentity(token);
11246 }
Stuart Scottd5463642015-04-02 18:00:02 -070011247 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040011248
Ricky Wai7097cc92018-01-23 04:09:45 +000011249 @Override
11250 public byte[] getNetworkWatchlistConfigHash() {
11251 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
11252 if (nwm == null) {
11253 loge("Unable to get NetworkWatchlistManager");
11254 return null;
11255 }
11256 // Redirect it to network watchlist service to access watchlist file and calculate hash.
11257 return nwm.getWatchlistConfigHash();
11258 }
11259
Hugo Benichibe0c7652016-05-31 16:28:06 +090011260 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090011261 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080011262 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090011263 }
Hugo Benichif4210292017-04-21 15:07:12 +090011264
11265 private static boolean toBool(int encodedBoolean) {
11266 return encodedBoolean != 0; // Only 0 means false.
11267 }
11268
11269 private static int encodeBool(boolean b) {
11270 return b ? 1 : 0;
11271 }
mswest4632928412018-03-12 10:34:34 -070011272
11273 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011274 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
11275 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
11276 @NonNull String[] args) {
11277 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
11278 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070011279 }
11280
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011281 private Boolean parseBooleanArgument(final String arg) {
11282 if ("true".equals(arg)) {
11283 return true;
11284 } else if ("false".equals(arg)) {
11285 return false;
11286 } else {
11287 return null;
11288 }
11289 }
11290
Chiachang Wang77ae8a02020-10-12 15:20:07 +080011291 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070011292 @Override
11293 public int onCommand(String cmd) {
11294 if (cmd == null) {
11295 return handleDefaultCommands(cmd);
11296 }
11297 final PrintWriter pw = getOutPrintWriter();
11298 try {
11299 switch (cmd) {
11300 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011301 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
11302 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070011303 final String action = getNextArg();
11304 if ("enable".equals(action)) {
11305 setAirplaneMode(true);
11306 return 0;
11307 } else if ("disable".equals(action)) {
11308 setAirplaneMode(false);
11309 return 0;
11310 } else if (action == null) {
11311 final ContentResolver cr = mContext.getContentResolver();
11312 final int enabled = Settings.Global.getInt(cr,
11313 Settings.Global.AIRPLANE_MODE_ON);
11314 pw.println(enabled == 0 ? "disabled" : "enabled");
11315 return 0;
11316 } else {
11317 onHelp();
11318 return -1;
11319 }
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011320 case "set-chain3-enabled": {
11321 final Boolean enabled = parseBooleanArgument(getNextArg());
11322 if (null == enabled) {
11323 onHelp();
11324 return -1;
11325 }
11326 Log.i(TAG, (enabled ? "En" : "Dis") + "abled FIREWALL_CHAIN_OEM_DENY_3");
11327 setFirewallChainEnabled(ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11328 enabled);
11329 return 0;
11330 }
11331 case "get-chain3-enabled": {
11332 final boolean chainEnabled = getFirewallChainEnabled(
11333 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3);
11334 pw.println("chain:" + (chainEnabled ? "enabled" : "disabled"));
11335 return 0;
11336 }
11337 case "set-package-networking-enabled": {
11338 final Boolean enabled = parseBooleanArgument(getNextArg());
11339 final String packageName = getNextArg();
11340 if (null == enabled || null == packageName) {
11341 onHelp();
11342 return -1;
11343 }
11344 // Throws NameNotFound if the package doesn't exist.
11345 final int appId = setPackageFirewallRule(
11346 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3,
11347 packageName, enabled ? FIREWALL_RULE_DEFAULT : FIREWALL_RULE_DENY);
11348 final String msg = (enabled ? "Enabled" : "Disabled")
11349 + " networking for " + packageName + ", appId " + appId;
11350 Log.i(TAG, msg);
11351 pw.println(msg);
11352 return 0;
11353 }
11354 case "get-package-networking-enabled": {
11355 final String packageName = getNextArg();
11356 final int rule = getPackageFirewallRule(
11357 ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3, packageName);
11358 if (FIREWALL_RULE_ALLOW == rule || FIREWALL_RULE_DEFAULT == rule) {
11359 pw.println(packageName + ":" + "allow");
11360 } else if (FIREWALL_RULE_DENY == rule) {
11361 pw.println(packageName + ":" + "deny");
11362 } else {
11363 throw new IllegalStateException("Unknown rule " + rule + " for package "
11364 + packageName);
11365 }
11366 return 0;
11367 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090011368 case "reevaluate":
11369 // Usage : adb shell cmd connectivity reevaluate <netId>
11370 // If netId is omitted, then reevaluate the default network
11371 final String netId = getNextArg();
11372 final NetworkAgentInfo nai;
11373 if (null == netId) {
11374 // Note that the command is running on the wrong thread to call this,
11375 // so this could in principle return stale data. But it can't crash.
11376 nai = getDefaultNetwork();
11377 } else {
11378 // If netId can't be parsed, this throws NumberFormatException, which
11379 // is passed back to adb who prints it.
11380 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
11381 }
11382 if (null == nai) {
11383 pw.println("Unknown network (net ID not found or no default network)");
11384 return 0;
11385 }
11386 Log.d(TAG, "Reevaluating network " + nai.network);
11387 reportNetworkConnectivity(nai.network, !nai.isValidated());
11388 return 0;
Junyu Lai452e4642023-10-05 17:21:19 +080011389 case "bpf-get-cgroup-program-id": {
11390 // Usage : adb shell cmd connectivity bpf-get-cgroup-program-id <type>
11391 // Get cgroup bpf program Id for the given type. See BpfUtils#getProgramId
11392 // for more detail.
11393 // If type can't be parsed, this throws NumberFormatException, which
11394 // is passed back to adb who prints it.
11395 final int type = Integer.parseInt(getNextArg());
Maciej Żenczykowskide9d3672023-10-25 17:34:26 +000011396 final int ret = BpfUtils.getProgramId(type);
Junyu Lai452e4642023-10-05 17:21:19 +080011397 pw.println(ret);
11398 return 0;
11399 }
mswest4632928412018-03-12 10:34:34 -070011400 default:
11401 return handleDefaultCommands(cmd);
11402 }
11403 } catch (Exception e) {
11404 pw.println(e);
11405 }
11406 return -1;
11407 }
11408
11409 @Override
11410 public void onHelp() {
11411 PrintWriter pw = getOutPrintWriter();
11412 pw.println("Connectivity service commands:");
11413 pw.println(" help");
11414 pw.println(" Print this help text.");
11415 pw.println(" airplane-mode [enable|disable]");
11416 pw.println(" Turn airplane mode on or off.");
11417 pw.println(" airplane-mode");
11418 pw.println(" Get airplane mode.");
Chalard Jeanc8fefb32023-09-05 21:41:13 +090011419 pw.println(" set-chain3-enabled [true|false]");
11420 pw.println(" Enable or disable FIREWALL_CHAIN_OEM_DENY_3 for debugging.");
11421 pw.println(" get-chain3-enabled");
11422 pw.println(" Returns whether FIREWALL_CHAIN_OEM_DENY_3 is enabled.");
11423 pw.println(" set-package-networking-enabled [true|false] [package name]");
11424 pw.println(" Set the deny bit in FIREWALL_CHAIN_OEM_DENY_3 to package. This has\n"
11425 + " no effect if the chain is disabled.");
11426 pw.println(" get-package-networking-enabled [package name]");
11427 pw.println(" Get the deny bit in FIREWALL_CHAIN_OEM_DENY_3 for package.");
mswest4632928412018-03-12 10:34:34 -070011428 }
11429 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011430
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090011431 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011432 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
11433 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
11434 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080011435 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011436 }
11437
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090011438 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
11439 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090011440 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
11441 final TransportInfo newInfo = nc.getTransportInfo();
11442 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
11443 return;
11444 }
11445 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090011446 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090011447 }
11448 }
11449
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011450 /**
11451 * @param connectionInfo the connection to resolve.
11452 * @return {@code uid} if the connection is found and the app has permission to observe it
11453 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
11454 * connection is not found.
11455 */
11456 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011457 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
11458 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
11459 }
11460
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090011461 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011462 connectionInfo.local, connectionInfo.remote);
11463
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011464 if (uid == INVALID_UID) return uid; // Not found.
11465
11466 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
11467 // VPN, if any, that applies to the UID that owns the connection.
Junyu Lai71b51532024-02-01 10:39:01 +080011468 if (hasNetworkStackPermission()) return uid;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090011469
11470 final NetworkAgentInfo vpn = getVpnForUid(uid);
11471 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090011472 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070011473 return INVALID_UID;
11474 }
11475
11476 return uid;
11477 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000011478
Benedict Wong493e04b2018-11-09 14:45:34 -080011479 /**
11480 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
11481 *
11482 * <p>The TestNetworkService must be run in the system server due to TUN creation.
11483 */
11484 @Override
11485 public IBinder startOrGetTestNetworkService() {
11486 synchronized (mTNSLock) {
11487 TestNetworkService.enforceTestNetworkPermissions(mContext);
11488
11489 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080011490 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080011491 }
11492
11493 return mTNS;
11494 }
11495 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080011496
Cody Kesting73708bf2019-12-18 10:57:50 -080011497 /**
11498 * Handler used for managing all Connectivity Diagnostics related functions.
11499 *
11500 * @see android.net.ConnectivityDiagnosticsManager
11501 *
11502 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
11503 */
11504 @VisibleForTesting
11505 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011506 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
11507
Cody Kesting73708bf2019-12-18 10:57:50 -080011508 /**
11509 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
11510 * android.net.ConnectivityDiagnosticsManager}.
11511 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
11512 * NetworkRequestInfo to be registered
11513 */
11514 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
11515
11516 /**
11517 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
11518 * android.net.ConnectivityDiagnosticsManager}.
11519 * obj = the IConnectivityDiagnosticsCallback to be unregistered
11520 * arg1 = the uid of the caller
11521 */
11522 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
11523
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011524 /**
11525 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011526 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011527 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
11528 * NetworkMonitor.
11529 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011530 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011531 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011532
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011533 /**
11534 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
11535 * been detected on the network.
11536 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
11537 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
11538 * arg2 = NetID.
11539 * data = PersistableBundle of extras passed from NetworkMonitor.
11540 */
11541 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
11542
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011543 /**
11544 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
11545 * the platform. This event will invoke {@link
11546 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
11547 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070011548 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011549 */
11550 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
11551
Cody Kesting73708bf2019-12-18 10:57:50 -080011552 private ConnectivityDiagnosticsHandler(Looper looper) {
11553 super(looper);
11554 }
11555
11556 @Override
11557 public void handleMessage(Message msg) {
11558 switch (msg.what) {
11559 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11560 handleRegisterConnectivityDiagnosticsCallback(
11561 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
11562 break;
11563 }
11564 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
11565 handleUnregisterConnectivityDiagnosticsCallback(
11566 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
11567 break;
11568 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090011569 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011570 final ConnectivityReportEvent reportEvent =
11571 (ConnectivityReportEvent) msg.obj;
11572
Aaron Huang959d3642021-01-21 15:47:41 +080011573 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011574 break;
11575 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011576 case EVENT_DATA_STALL_SUSPECTED: {
11577 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080011578 final Pair<Long, PersistableBundle> arg =
11579 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011580 if (nai == null) break;
11581
Aaron Huang959d3642021-01-21 15:47:41 +080011582 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011583 break;
11584 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011585 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070011586 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011587 break;
11588 }
11589 default: {
11590 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
11591 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011592 }
11593 }
11594 }
11595
11596 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
11597 @VisibleForTesting
11598 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
11599 @NonNull private final IConnectivityDiagnosticsCallback mCb;
11600 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011601 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011602
11603 @VisibleForTesting
11604 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011605 @NonNull IConnectivityDiagnosticsCallback cb,
11606 @NonNull NetworkRequestInfo nri,
11607 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011608 mCb = cb;
11609 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011610 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080011611 }
11612
11613 @Override
11614 public void binderDied() {
11615 log("ConnectivityDiagnosticsCallback IBinder died.");
11616 unregisterConnectivityDiagnosticsCallback(mCb);
11617 }
11618 }
11619
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011620 /**
11621 * Class used for sending information from {@link
11622 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
11623 */
11624 private static class NetworkTestedResults {
11625 private final int mNetId;
11626 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011627 @Nullable private final String mRedirectUrl;
11628
11629 private NetworkTestedResults(
11630 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
11631 mNetId = netId;
11632 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011633 mRedirectUrl = redirectUrl;
11634 }
11635 }
11636
11637 /**
11638 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
11639 * ConnectivityDiagnosticsHandler}.
11640 */
11641 private static class ConnectivityReportEvent {
11642 private final long mTimestampMillis;
11643 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080011644 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011645
Aaron Huang959d3642021-01-21 15:47:41 +080011646 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
11647 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011648 mTimestampMillis = timestampMillis;
11649 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080011650 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011651 }
11652 }
11653
Cody Kestingf1120be2020-08-03 18:01:40 -070011654 /**
11655 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
11656 * ConnectivityDiagnosticsHandler}.
11657 */
11658 private static class ReportedNetworkConnectivityInfo {
11659 public final boolean hasConnectivity;
11660 public final boolean isNetworkRevalidating;
11661 public final int reporterUid;
11662 @NonNull public final NetworkAgentInfo nai;
11663
11664 private ReportedNetworkConnectivityInfo(
11665 boolean hasConnectivity,
11666 boolean isNetworkRevalidating,
11667 int reporterUid,
11668 @NonNull NetworkAgentInfo nai) {
11669 this.hasConnectivity = hasConnectivity;
11670 this.isNetworkRevalidating = isNetworkRevalidating;
11671 this.reporterUid = reporterUid;
11672 this.nai = nai;
11673 }
11674 }
11675
Cody Kesting73708bf2019-12-18 10:57:50 -080011676 private void handleRegisterConnectivityDiagnosticsCallback(
11677 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
11678 ensureRunningOnConnectivityServiceThread();
11679
11680 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080011681 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011682 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
11683
James Mattis64b8b0f2020-11-24 17:40:49 -080011684 // Connectivity Diagnostics are meant to be used with a single network request. It would be
11685 // confusing for these networks to change when an NRI is satisfied in another layer.
11686 if (nri.isMultilayerRequest()) {
11687 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
11688 + "network requests.");
11689 }
11690
Cody Kesting73708bf2019-12-18 10:57:50 -080011691 // This means that the client registered the same callback multiple times. Do
11692 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080011693 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011694 if (VDBG) log("Diagnostics callback is already registered");
11695
11696 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11697 // incremented when the NetworkRequestInfo is created as part of
11698 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011699 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080011700 return;
11701 }
11702
Cody Kesting31f1ff62020-03-05 10:46:02 -080011703 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080011704
11705 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080011706 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011707 } catch (RemoteException e) {
11708 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080011709 return;
11710 }
11711
11712 // Once registered, provide ConnectivityReports for matching Networks
11713 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
11714 synchronized (mNetworkForNetId) {
11715 for (int i = 0; i < mNetworkForNetId.size(); i++) {
11716 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080011717 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
11718 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080011719 matchingNetworks.add(nai);
11720 }
11721 }
11722 }
11723 for (final NetworkAgentInfo nai : matchingNetworks) {
11724 final ConnectivityReport report = nai.getConnectivityReport();
11725 if (report == null) {
11726 continue;
11727 }
Junyu Lai71b51532024-02-01 10:39:01 +080011728 if (!hasConnectivityDiagnosticsPermissions(
Cody Kestingb77bf702020-02-12 14:50:58 -080011729 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11730 continue;
11731 }
11732
11733 try {
11734 cb.onConnectivityReportAvailable(report);
11735 } catch (RemoteException e) {
11736 // Exception while sending the ConnectivityReport. Move on to the next network.
11737 }
Cody Kesting73708bf2019-12-18 10:57:50 -080011738 }
11739 }
11740
11741 private void handleUnregisterConnectivityDiagnosticsCallback(
11742 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
11743 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011744 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080011745
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011746 final ConnectivityDiagnosticsCallbackInfo cbInfo =
11747 mConnectivityDiagnosticsCallbacks.remove(iCb);
11748 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080011749 if (VDBG) log("Removing diagnostics callback that is not currently registered");
11750 return;
11751 }
11752
Cody Kesting2b1a61c2020-03-30 12:43:49 -070011753 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080011754
Cody Kesting70fa2b22020-12-02 12:16:56 -080011755 // Caller's UID must either be the registrants (if they are unregistering) or the System's
11756 // (if the Binder died)
11757 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
11758 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080011759 return;
11760 }
11761
Cody Kesting46cb1672020-03-04 13:35:20 -080011762 // Decrement the reference count for this NetworkRequestInfo. The reference count is
11763 // incremented when the NetworkRequestInfo is created as part of
11764 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080011765 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080011766
Cody Kesting31f1ff62020-03-05 10:46:02 -080011767 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080011768 }
11769
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011770 private void handleNetworkTestedWithExtras(
11771 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
11772 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080011773 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011774 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011775 final ConnectivityReport report =
11776 new ConnectivityReport(
11777 reportEvent.mNai.network,
11778 reportEvent.mTimestampMillis,
11779 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011780 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011781 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080011782 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070011783
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011784 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011785 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011786 for (final IConnectivityDiagnosticsCallback cb : results) {
11787 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080011788 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011789 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070011790 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011791 }
11792 }
11793 }
11794
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011795 private void handleDataStallSuspected(
11796 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
11797 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080011798 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011799 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011800 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080011801 new DataStallReport(
11802 nai.network,
11803 timestampMillis,
11804 detectionMethod,
11805 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080011806 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080011807 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011808 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011809 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080011810 for (final IConnectivityDiagnosticsCallback cb : results) {
11811 try {
11812 cb.onDataStallSuspected(report);
11813 } catch (RemoteException ex) {
11814 loge("Error invoking onDataStallSuspected", ex);
11815 }
11816 }
11817 }
11818
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011819 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070011820 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
11821 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
11822 final ConnectivityReport cachedReport = nai.getConnectivityReport();
11823
11824 // If the Network is being re-validated as a result of this call to
11825 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
11826 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011827 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070011828 getMatchingPermissionedCallbacks(
11829 nai,
11830 reportedNetworkConnectivityInfo.isNetworkRevalidating
11831 ? Process.INVALID_UID
11832 : reportedNetworkConnectivityInfo.reporterUid);
11833
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011834 for (final IConnectivityDiagnosticsCallback cb : results) {
11835 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070011836 cb.onNetworkConnectivityReported(
11837 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011838 } catch (RemoteException ex) {
11839 loge("Error invoking onNetworkConnectivityReported", ex);
11840 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011841
11842 // If the Network isn't re-validating, also provide the cached report. If there is no
11843 // cached report, the Network is still being validated and a report will be sent once
11844 // validation is complete. Note that networks which never undergo validation will still
11845 // have a cached ConnectivityReport with RESULT_SKIPPED.
11846 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
11847 try {
11848 cb.onConnectivityReportAvailable(cachedReport);
11849 } catch (RemoteException ex) {
11850 loge("Error invoking onConnectivityReportAvailable", ex);
11851 }
11852 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080011853 }
11854 }
11855
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011856 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090011857 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
11858 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080011859 sanitized.setUids(null);
11860 sanitized.setAdministratorUids(new int[0]);
11861 sanitized.setOwnerUid(Process.INVALID_UID);
11862 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080011863 }
11864
Cody Kestingf1120be2020-08-03 18:01:40 -070011865 /**
11866 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
11867 *
11868 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
11869 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011870 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070011871 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011872 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080011873 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011874 mConnectivityDiagnosticsCallbacks.entrySet()) {
11875 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
11876 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070011877
James Mattis64b8b0f2020-11-24 17:40:49 -080011878 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070011879 if (!nai.satisfies(nri.mRequests.get(0))) {
11880 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011881 }
Cody Kestingf1120be2020-08-03 18:01:40 -070011882
11883 // UID for this callback must either be:
11884 // - INVALID_UID (which sends callbacks to all UIDs), or
11885 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
11886 // notified as a result)
11887 if (uid != Process.INVALID_UID && uid != nri.mUid) {
11888 continue;
11889 }
11890
Junyu Lai71b51532024-02-01 10:39:01 +080011891 if (!hasConnectivityDiagnosticsPermissions(
Cody Kestingf1120be2020-08-03 18:01:40 -070011892 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
11893 continue;
11894 }
11895
11896 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011897 }
11898 return results;
11899 }
11900
Cody Kesting7474f672021-05-11 14:22:40 -070011901 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
11902 @NonNull NetworkAgentInfo nai) {
11903 // TODO(b/188483916): replace with a transport-agnostic location-aware check
11904 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
11905 }
11906
Cody Kesting160ef392021-05-05 13:17:22 -070011907 private boolean hasLocationPermission(String packageName, int uid) {
11908 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
11909 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
11910 // call in a try-catch.
11911 try {
11912 if (!mLocationPermissionChecker.checkLocationPermission(
11913 packageName, null /* featureId */, uid, null /* message */)) {
11914 return false;
11915 }
11916 } catch (SecurityException e) {
11917 return false;
11918 }
11919
11920 return true;
11921 }
11922
11923 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
11924 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090011925 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070011926 && virtual.networkCapabilities.getOwnerUid() == uid
11927 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
11928 return true;
11929 }
11930 }
11931
11932 return false;
11933 }
11934
Junyu Lai71b51532024-02-01 10:39:01 +080011935 @CheckResult
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011936 @VisibleForTesting
Junyu Lai71b51532024-02-01 10:39:01 +080011937 boolean hasConnectivityDiagnosticsPermissions(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011938 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
Junyu Lai71b51532024-02-01 10:39:01 +080011939 if (hasNetworkStackPermission(callbackPid, callbackUid)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011940 return true;
11941 }
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011942 if (mAllowSysUiConnectivityReports
Junyu Lai71b51532024-02-01 10:39:01 +080011943 && hasSystemBarServicePermission(callbackPid, callbackUid)) {
Quang Anh Luong28eefef2023-11-07 09:43:41 +090011944 return true;
11945 }
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011946
Cody Kesting160ef392021-05-05 13:17:22 -070011947 // Administrator UIDs also contains the Owner UID
11948 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
11949 if (!CollectionUtils.contains(administratorUids, callbackUid)
11950 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011951 return false;
11952 }
11953
Cody Kesting7474f672021-05-11 14:22:40 -070011954 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
11955 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011956 }
11957
Cody Kestingd199a9d2019-12-17 12:55:28 -080011958 @Override
11959 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011960 @NonNull IConnectivityDiagnosticsCallback callback,
11961 @NonNull NetworkRequest request,
11962 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070011963 Objects.requireNonNull(callback, "callback must not be null");
11964 Objects.requireNonNull(request, "request must not be null");
11965 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
11966
Cody Kesting73708bf2019-12-18 10:57:50 -080011967 if (request.legacyType != TYPE_NONE) {
11968 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
11969 + " Please use NetworkCapabilities instead.");
11970 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090011971 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080011972 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011973
11974 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
11975 // and administrator uids to be safe.
11976 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080011977 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011978
11979 final NetworkRequest requestWithId =
11980 new NetworkRequest(
11981 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
11982
11983 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
11984 //
11985 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
11986 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
11987 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011988 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080011989 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080011990 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080011991
11992 mConnectivityDiagnosticsHandler.sendMessage(
11993 mConnectivityDiagnosticsHandler.obtainMessage(
11994 ConnectivityDiagnosticsHandler
11995 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
11996 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080011997 }
11998
11999 @Override
12000 public void unregisterConnectivityDiagnosticsCallback(
12001 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012002 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080012003 mConnectivityDiagnosticsHandler.sendMessage(
12004 mConnectivityDiagnosticsHandler.obtainMessage(
12005 ConnectivityDiagnosticsHandler
12006 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090012007 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080012008 0,
12009 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080012010 }
Cody Kestingf53a0752020-04-15 12:33:28 -070012011
Yan Yanfe96dde2022-12-05 23:00:01 +000012012 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
12013 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
12014 if (underlyingNetworks == null) return false;
12015
12016 for (Network network : underlyingNetworks) {
12017 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
12018 return true;
12019 }
12020 }
12021 return false;
12022 }
12023
Cody Kestingf53a0752020-04-15 12:33:28 -070012024 @Override
12025 public void simulateDataStall(int detectionMethod, long timestampMillis,
12026 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070012027 Objects.requireNonNull(network, "network must not be null");
12028 Objects.requireNonNull(extras, "extras must not be null");
12029
paulhu3ffffe72021-09-16 10:15:22 +080012030 enforceAnyPermissionOf(mContext,
12031 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070012032 android.Manifest.permission.NETWORK_STACK);
12033 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000012034 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
12035 throw new SecurityException(
12036 "Data Stall simulation is only possible for test networks or networks built on"
12037 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070012038 }
12039
12040 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000012041 if (nai == null
12042 || (nai.creatorUid != mDeps.getCallingUid()
12043 && nai.creatorUid != Process.SYSTEM_UID)) {
12044 throw new SecurityException(
12045 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070012046 }
12047
Cody Kesting652e3ec2020-05-21 12:08:21 -070012048 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
12049 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
12050 // Data Stall information as a DataStallReportParcelable and passing to
12051 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
12052 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070012053 final DataStallReportParcelable p = new DataStallReportParcelable();
12054 p.timestampMillis = timestampMillis;
12055 p.detectionMethod = detectionMethod;
12056
12057 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
12058 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
12059 }
12060 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
12061 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
12062 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
12063 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
12064 }
12065
Serik Beketayevec8ad212020-12-07 22:43:07 -080012066 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070012067 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012068
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012069 /**
12070 * Class to hold the information for network activity change event from idle timers
12071 * {@link NetdCallback#onInterfaceClassActivityChanged(boolean, int, long, int)}
12072 */
12073 private static final class NetworkActivityParams {
12074 public final boolean isActive;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012075 // If TrackMultiNetworkActivities is enabled, idleTimer label is netid.
12076 // If TrackMultiNetworkActivities is disabled, idleTimer label is transport type.
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012077 public final int label;
12078 public final long timestampNs;
12079 // Uid represents the uid that was responsible for waking the radio.
12080 // -1 for no uid and uid is -1 if isActive is false.
12081 public final int uid;
12082
12083 NetworkActivityParams(boolean isActive, int label, long timestampNs, int uid) {
12084 this.isActive = isActive;
12085 this.label = label;
12086 this.timestampNs = timestampNs;
12087 this.uid = uid;
12088 }
12089 }
12090
lucaslin66f44212021-02-23 01:12:55 +080012091 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
12092 @Override
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012093 public void onInterfaceClassActivityChanged(boolean isActive, int label,
lucaslin66f44212021-02-23 01:12:55 +080012094 long timestampNs, int uid) {
Motomu Utsumi5dfaf4e2023-05-29 17:02:16 +090012095 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY,
12096 new NetworkActivityParams(isActive, label, timestampNs, uid)));
lucaslin66f44212021-02-23 01:12:55 +080012097 }
lucaslin37a16d92021-01-21 19:48:09 +080012098
12099 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090012100 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012101 mHandler.post(() -> {
12102 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090012103 nai.clatd.handleInterfaceLinkStateChanged(iface, up);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012104 }
12105 });
lucaslin37a16d92021-01-21 19:48:09 +080012106 }
12107
12108 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090012109 public void onInterfaceRemoved(@NonNull String iface) {
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012110 mHandler.post(() -> {
12111 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti3b817cb2023-09-26 13:40:13 +090012112 nai.clatd.handleInterfaceRemoved(iface);
Chalard Jean5d05c4b2023-08-24 15:43:33 +090012113 }
12114 });
lucaslin66f44212021-02-23 01:12:55 +080012115 }
12116 }
12117
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012118 private final boolean mTrackMultiNetworkActivities;
lucaslin1a8b4c62021-01-21 02:02:55 +080012119 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
12120
12121 /**
12122 * Class used for updating network activity tracking with netd and notify network activity
12123 * changes.
12124 */
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012125 @VisibleForTesting
12126 public static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080012127 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080012128 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080012129 private final INetd mNetd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012130 private final Handler mHandler;
lucaslin1193a5d2021-01-21 02:04:15 +080012131 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
12132 new RemoteCallbackList<>();
12133 // Indicate the current system default network activity is active or not.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012134 // This needs to be volatile to allow non handler threads to read this value without lock.
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012135 // If there is no default network, default network is considered active to keep the existing
12136 // behavior. Initial value is used until first connect to the default network.
12137 private volatile boolean mIsDefaultNetworkActive = true;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012138 private Network mDefaultNetwork;
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012139 // Key is netId. Value is configured idle timer information.
12140 private final SparseArray<IdleTimerParams> mActiveIdleTimers = new SparseArray<>();
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012141 private final boolean mTrackMultiNetworkActivities;
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012142 // Store netIds of Wi-Fi networks whose idletimers report that they are active
12143 private final Set<Integer> mActiveWifiNetworks = new ArraySet<>();
12144 // Store netIds of cellular networks whose idletimers report that they are active
12145 private final Set<Integer> mActiveCellularNetworks = new ArraySet<>();
lucaslin1a8b4c62021-01-21 02:02:55 +080012146
Chalard Jean46bfbf02022-02-02 00:56:25 +090012147 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080012148 public final int timeout;
12149 public final int transportType;
12150
12151 IdleTimerParams(int timeout, int transport) {
12152 this.timeout = timeout;
12153 this.transportType = transport;
12154 }
12155 }
12156
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012157 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull INetd netd,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012158 @NonNull Handler handler, boolean trackMultiNetworkActivities) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012159 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080012160 mNetd = netd;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012161 mHandler = handler;
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012162 mTrackMultiNetworkActivities = trackMultiNetworkActivities;
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012163 }
12164
12165 private void ensureRunningOnConnectivityServiceThread() {
12166 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
12167 throw new IllegalStateException("Not running on ConnectivityService thread: "
12168 + Thread.currentThread().getName());
12169 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012170 }
12171
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012172 /**
12173 * Update network activity and call BatteryStats to update radio power state if the
12174 * mobile or Wi-Fi activity is changed.
12175 * LegacyNetworkActivityTracker considers the mobile network is active if at least one
12176 * mobile network is active since BatteryStatsService only maintains a single power state
12177 * for the mobile network.
12178 * The Wi-Fi network is also the same.
12179 *
12180 * {@link #setupDataActivityTracking} and {@link #removeDataActivityTracking} use
12181 * TRANSPORT_CELLULAR as the transportType argument if the network has both cell and Wi-Fi
12182 * transports.
12183 */
12184 private void maybeUpdateRadioPowerState(final int netId, final int transportType,
12185 final boolean isActive, final int uid) {
12186 if (transportType != TRANSPORT_WIFI && transportType != TRANSPORT_CELLULAR) {
12187 Log.e(TAG, "Unexpected transportType in maybeUpdateRadioPowerState: "
12188 + transportType);
12189 return;
12190 }
12191 final Set<Integer> activeNetworks = transportType == TRANSPORT_WIFI
12192 ? mActiveWifiNetworks : mActiveCellularNetworks;
12193
12194 final boolean wasEmpty = activeNetworks.isEmpty();
12195 if (isActive) {
12196 activeNetworks.add(netId);
12197 } else {
12198 activeNetworks.remove(netId);
12199 }
12200
12201 if (wasEmpty != activeNetworks.isEmpty()) {
12202 updateRadioPowerState(isActive, transportType, uid);
12203 }
12204 }
12205
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012206 private void handleDefaultNetworkActivity(final int transportType,
12207 final boolean isActive, final long timestampNs) {
12208 mIsDefaultNetworkActive = isActive;
12209 sendDataActivityBroadcast(transportTypeToLegacyType(transportType),
12210 isActive, timestampNs);
12211 if (isActive) {
12212 reportNetworkActive();
12213 }
12214 }
12215
12216 private void handleReportNetworkActivityWithNetIdLabel(
12217 NetworkActivityParams activityParams) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012218 final int netId = activityParams.label;
12219 final IdleTimerParams idleTimerParams = mActiveIdleTimers.get(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012220 if (idleTimerParams == null) {
12221 // This network activity change is not tracked anymore
12222 // This can happen if netd callback post activity change event message but idle
12223 // timer is removed before processing this message.
12224 return;
12225 }
12226 // TODO: if a network changes transports, storing the transport type in the
12227 // IdleTimerParams is not correct. Consider getting it from the network's
12228 // NetworkCapabilities instead.
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012229 final int transportType = idleTimerParams.transportType;
12230 maybeUpdateRadioPowerState(netId, transportType,
12231 activityParams.isActive, activityParams.uid);
12232
12233 if (mDefaultNetwork == null || mDefaultNetwork.netId != netId) {
12234 // This activity change is not for the default network.
12235 return;
12236 }
12237
12238 handleDefaultNetworkActivity(transportType, activityParams.isActive,
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012239 activityParams.timestampNs);
12240 }
12241
12242 private void handleReportNetworkActivityWithTransportTypeLabel(
12243 NetworkActivityParams activityParams) {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012244 if (mActiveIdleTimers.size() == 0) {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012245 // This activity change is not for the current default network.
12246 // This can happen if netd callback post activity change event message but
12247 // the default network is lost before processing this message.
12248 return;
12249 }
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012250 handleDefaultNetworkActivity(activityParams.label, activityParams.isActive,
12251 activityParams.timestampNs);
12252 }
12253
12254 /**
12255 * Handle network activity change
12256 */
12257 public void handleReportNetworkActivity(NetworkActivityParams activityParams) {
12258 ensureRunningOnConnectivityServiceThread();
12259 if (mTrackMultiNetworkActivities) {
12260 handleReportNetworkActivityWithNetIdLabel(activityParams);
12261 } else {
12262 handleReportNetworkActivityWithTransportTypeLabel(activityParams);
lucaslin66f44212021-02-23 01:12:55 +080012263 }
12264 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012265
lucaslin1193a5d2021-01-21 02:04:15 +080012266 private void reportNetworkActive() {
12267 final int length = mNetworkActivityListeners.beginBroadcast();
12268 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
12269 try {
12270 for (int i = 0; i < length; i++) {
12271 try {
12272 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
12273 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012274 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080012275 }
12276 }
12277 } finally {
12278 mNetworkActivityListeners.finishBroadcast();
12279 }
12280 }
12281
lucaslin1a8b4c62021-01-21 02:02:55 +080012282 // This is deprecated and only to support legacy use cases.
12283 private int transportTypeToLegacyType(int type) {
12284 switch (type) {
12285 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012286 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080012287 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012288 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080012289 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012290 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080012291 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090012292 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080012293 default:
12294 loge("Unexpected transport in transportTypeToLegacyType: " + type);
12295 }
12296 return ConnectivityManager.TYPE_NONE;
12297 }
12298
12299 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
12300 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
12301 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
12302 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
12303 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
12304 final long ident = Binder.clearCallingIdentity();
12305 try {
12306 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
12307 RECEIVE_DATA_ACTIVITY_CHANGE,
12308 null /* resultReceiver */,
12309 null /* scheduler */,
12310 0 /* initialCode */,
12311 null /* initialData */,
12312 null /* initialExtra */);
12313 } finally {
12314 Binder.restoreCallingIdentity(ident);
12315 }
12316 }
12317
12318 /**
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012319 * Get idle timer label
12320 */
12321 @VisibleForTesting
12322 public static int getIdleTimerLabel(final boolean trackMultiNetworkActivities,
12323 final int netId, final int transportType) {
12324 return trackMultiNetworkActivities ? netId : transportType;
12325 }
12326
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012327 private boolean maybeCreateIdleTimer(
12328 String iface, int netId, int timeout, int transportType) {
12329 if (timeout <= 0 || iface == null) return false;
12330 try {
12331 final String label = Integer.toString(getIdleTimerLabel(
12332 mTrackMultiNetworkActivities, netId, transportType));
12333 mNetd.idletimerAddInterface(iface, timeout, label);
12334 mActiveIdleTimers.put(netId, new IdleTimerParams(timeout, transportType));
12335 return true;
12336 } catch (Exception e) {
12337 loge("Exception in createIdleTimer", e);
12338 return false;
12339 }
12340 }
12341
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012342 /**
lucaslin1a8b4c62021-01-21 02:02:55 +080012343 * Setup data activity tracking for the given network.
12344 *
12345 * Every {@code setupDataActivityTracking} should be paired with a
12346 * {@link #removeDataActivityTracking} for cleanup.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012347 *
12348 * @return true if the idleTimer is added to the network, false otherwise
lucaslin1a8b4c62021-01-21 02:02:55 +080012349 */
Motomu Utsumi6225d572023-05-29 15:08:57 +090012350 private boolean setupDataActivityTracking(NetworkAgentInfo networkAgent) {
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012351 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012352 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012353 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012354
12355 final int timeout;
12356 final int type;
12357
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012358 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12359 // Do not track VPN network.
12360 return false;
12361 } else if (networkAgent.networkCapabilities.hasTransport(
lucaslin1a8b4c62021-01-21 02:02:55 +080012362 NetworkCapabilities.TRANSPORT_CELLULAR)) {
12363 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012364 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080012365 10);
12366 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12367 } else if (networkAgent.networkCapabilities.hasTransport(
12368 NetworkCapabilities.TRANSPORT_WIFI)) {
12369 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080012370 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080012371 15);
12372 type = NetworkCapabilities.TRANSPORT_WIFI;
12373 } else {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012374 return false; // do not track any other networks
lucaslin1a8b4c62021-01-21 02:02:55 +080012375 }
12376
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012377 final boolean hasIdleTimer = maybeCreateIdleTimer(iface, netId, timeout, type);
12378 if (hasIdleTimer || !mTrackMultiNetworkActivities) {
12379 // If trackMultiNetwork is disabled, NetworkActivityTracker updates radio power
12380 // state in all cases. If trackMultiNetwork is enabled, it updates radio power
12381 // state only about a network that has an idletimer.
12382 maybeUpdateRadioPowerState(netId, type, true /* isActive */, NO_UID);
lucaslin1a8b4c62021-01-21 02:02:55 +080012383 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012384 return hasIdleTimer;
lucaslin1a8b4c62021-01-21 02:02:55 +080012385 }
12386
12387 /**
12388 * Remove data activity tracking when network disconnects.
12389 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012390 public void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
12391 ensureRunningOnConnectivityServiceThread();
lucaslin1a8b4c62021-01-21 02:02:55 +080012392 final String iface = networkAgent.linkProperties.getInterfaceName();
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012393 final int netId = networkAgent.network().netId;
lucaslin1a8b4c62021-01-21 02:02:55 +080012394 final NetworkCapabilities caps = networkAgent.networkCapabilities;
12395
lucaslinb961efc2021-01-21 02:03:17 +080012396 if (iface == null) return;
12397
12398 final int type;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012399 if (!networkAgent.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_VPN)) {
12400 // Do not track VPN network.
12401 return;
12402 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
lucaslinb961efc2021-01-21 02:03:17 +080012403 type = NetworkCapabilities.TRANSPORT_CELLULAR;
12404 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
12405 type = NetworkCapabilities.TRANSPORT_WIFI;
12406 } else {
12407 return; // do not track any other networks
12408 }
12409
12410 try {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012411 maybeUpdateRadioPowerState(netId, type, false /* isActive */, NO_UID);
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012412 final IdleTimerParams params = mActiveIdleTimers.get(netId);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012413 if (params == null) {
12414 // IdleTimer is not added if the configured timeout is 0 or negative value
12415 return;
lucaslin1a8b4c62021-01-21 02:02:55 +080012416 }
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012417 mActiveIdleTimers.remove(netId);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012418 final String label = Integer.toString(getIdleTimerLabel(
12419 mTrackMultiNetworkActivities, netId, params.transportType));
12420 // The call fails silently if no idle timer setup for this interface
12421 mNetd.idletimerRemoveInterface(iface, params.timeout, label);
lucaslinb961efc2021-01-21 02:03:17 +080012422 } catch (Exception e) {
12423 // You shall not crash!
12424 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080012425 }
12426 }
12427
Motomu Utsumi6225d572023-05-29 15:08:57 +090012428 private void updateDefaultNetworkActivity(NetworkAgentInfo defaultNetwork,
12429 boolean hasIdleTimer) {
12430 if (defaultNetwork != null) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012431 mDefaultNetwork = defaultNetwork.network();
Motomu Utsumi6225d572023-05-29 15:08:57 +090012432 mIsDefaultNetworkActive = true;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012433 // If only the default network is tracked, callbacks are called only when the
12434 // network has the idle timer.
12435 if (mTrackMultiNetworkActivities || hasIdleTimer) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012436 reportNetworkActive();
12437 }
12438 } else {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012439 mDefaultNetwork = null;
Motomu Utsumi51e7a602023-07-31 19:26:18 +090012440 // If there is no default network, default network is considered active to keep the
12441 // existing behavior.
12442 mIsDefaultNetworkActive = true;
Motomu Utsumi6225d572023-05-29 15:08:57 +090012443 }
12444 }
12445
lucaslin1a8b4c62021-01-21 02:02:55 +080012446 /**
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012447 * Update the default network this class tracks the activity of.
lucaslin1a8b4c62021-01-21 02:02:55 +080012448 */
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012449 public void updateDefaultNetwork(NetworkAgentInfo newNetwork,
lucaslin1a8b4c62021-01-21 02:02:55 +080012450 NetworkAgentInfo oldNetwork) {
Motomu Utsumie0ecaea2023-05-30 19:24:31 +090012451 ensureRunningOnConnectivityServiceThread();
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012452 // If TrackMultiNetworkActivities is enabled, devices add idleTimer when the network is
12453 // first connected and remove when the network is disconnected.
12454 // If TrackMultiNetworkActivities is disabled, devices add idleTimer when the network
12455 // becomes the default network and remove when the network becomes no longer the default
12456 // network.
Motomu Utsumi6225d572023-05-29 15:08:57 +090012457 boolean hasIdleTimer = false;
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012458 if (!mTrackMultiNetworkActivities && newNetwork != null) {
Motomu Utsumi6225d572023-05-29 15:08:57 +090012459 hasIdleTimer = setupDataActivityTracking(newNetwork);
lucaslin1a8b4c62021-01-21 02:02:55 +080012460 }
Motomu Utsumi6225d572023-05-29 15:08:57 +090012461 updateDefaultNetworkActivity(newNetwork, hasIdleTimer);
Motomu Utsumi1f5ffa42023-05-29 16:07:19 +090012462 if (!mTrackMultiNetworkActivities && oldNetwork != null) {
lucaslin1a8b4c62021-01-21 02:02:55 +080012463 removeDataActivityTracking(oldNetwork);
12464 }
12465 }
lucaslinb961efc2021-01-21 02:03:17 +080012466
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012467 private void updateRadioPowerState(boolean isActive, int transportType, int uid) {
lucaslinb961efc2021-01-21 02:03:17 +080012468 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
12469 switch (transportType) {
12470 case NetworkCapabilities.TRANSPORT_CELLULAR:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012471 bs.reportMobileRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012472 break;
12473 case NetworkCapabilities.TRANSPORT_WIFI:
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012474 bs.reportWifiRadioPowerState(isActive, uid);
lucaslinb961efc2021-01-21 02:03:17 +080012475 break;
12476 default:
12477 logw("Untracked transport type:" + transportType);
12478 }
12479 }
lucaslin1193a5d2021-01-21 02:04:15 +080012480
12481 public boolean isDefaultNetworkActive() {
Motomu Utsumic298cf02023-05-31 12:06:12 +090012482 return mIsDefaultNetworkActive;
lucaslin1193a5d2021-01-21 02:04:15 +080012483 }
12484
12485 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
12486 mNetworkActivityListeners.register(l);
12487 }
12488
12489 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
12490 mNetworkActivityListeners.unregister(l);
12491 }
lucaslin012f7a12021-01-21 02:04:35 +080012492
12493 public void dump(IndentingPrintWriter pw) {
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012494 pw.print("mTrackMultiNetworkActivities="); pw.println(mTrackMultiNetworkActivities);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012495 pw.print("mIsDefaultNetworkActive="); pw.println(mIsDefaultNetworkActive);
Motomu Utsumi5fce43e2023-05-29 15:21:43 +090012496 pw.print("mDefaultNetwork="); pw.println(mDefaultNetwork);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012497 pw.println("Idle timers:");
12498 try {
Motomu Utsumi473c38d2023-05-29 16:53:57 +090012499 for (int i = 0; i < mActiveIdleTimers.size(); i++) {
12500 pw.print(" "); pw.print(mActiveIdleTimers.keyAt(i)); pw.println(":");
12501 final IdleTimerParams params = mActiveIdleTimers.valueAt(i);
lucaslin012f7a12021-01-21 02:04:35 +080012502 pw.print(" timeout="); pw.print(params.timeout);
12503 pw.print(" type="); pw.println(params.transportType);
12504 }
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012505 pw.println("WiFi active networks: " + mActiveWifiNetworks);
12506 pw.println("Cellular active networks: " + mActiveCellularNetworks);
Motomu Utsumic298cf02023-05-31 12:06:12 +090012507 } catch (Exception e) {
Motomu Utsumidb537ac2023-06-01 11:56:20 +090012508 // mActiveIdleTimers, mActiveWifiNetworks, and mActiveCellularNetworks should only
12509 // be accessed from handler thread, except dump(). As dump() is never called in
12510 // normal usage, it would be needlessly expensive to lock the collection only for
12511 // its benefit. Also, they are not expected to be updated frequently.
Motomu Utsumic298cf02023-05-31 12:06:12 +090012512 // So catching the exception and logging.
12513 pw.println("Failed to dump NetworkActivityTracker: " + e);
lucaslin012f7a12021-01-21 02:04:35 +080012514 }
12515 }
lucaslin1a8b4c62021-01-21 02:02:55 +080012516 }
James Mattis47db0582021-01-01 14:13:35 -080012517
Daniel Brightf9e945b2020-06-15 16:10:01 -070012518 /**
12519 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
12520 *
12521 * @param socketInfo the socket information
12522 * @param callback the callback to register
12523 */
12524 @Override
12525 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
12526 @NonNull final IQosCallback callback) {
12527 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
12528 if (nai == null || nai.networkCapabilities == null) {
12529 try {
12530 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
12531 } catch (final RemoteException ex) {
12532 loge("registerQosCallbackInternal: RemoteException", ex);
12533 }
12534 return;
12535 }
12536 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
12537 }
12538
12539 /**
12540 * Register a {@link IQosCallback} with base {@link QosFilter}.
12541 *
12542 * @param filter the filter to register
12543 * @param callback the callback to register
12544 * @param nai the agent information related to the filter's network
12545 */
12546 @VisibleForTesting
12547 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
12548 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012549 Objects.requireNonNull(filter, "filter must be non-null");
12550 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012551
12552 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080012553 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
12554 // on this network is unregistered when the app loses permission or b) no QoS
12555 // callbacks are sent for restricted networks unless the app currently has permission
12556 // to access restricted networks.
12557 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070012558 }
12559 mQosCallbackTracker.registerCallback(callback, filter, nai);
12560 }
12561
12562 /**
12563 * Unregisters the given callback.
12564 *
12565 * @param callback the callback to unregister
12566 */
12567 @Override
12568 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080012569 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070012570 mQosCallbackTracker.unregisterCallback(callback);
12571 }
James Mattis47db0582021-01-01 14:13:35 -080012572
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012573 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
12574 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
12575 // Enterprise device can be fully managed like device owner and such use case
12576 // also should be supported. Calling app check for work profile and fully managed device
12577 // is already done in DevicePolicyManager.
12578 // This check is an extra caution to be sure device is fully managed or not.
12579 final UserManager um = mContext.getSystemService(UserManager.class);
12580 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
12581 if (um.isManagedProfile(profile.getIdentifier())) {
12582 return true;
12583 }
Chalard Jeandf29a852023-05-29 17:02:43 +090012584 if (mDeps.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012585 return false;
12586 }
12587
James Mattis45d81842021-01-10 14:24:24 -080012588 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012589 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012590 *
12591 * See the documentation for the individual preferences for a description of the supported
12592 * behaviors.
12593 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012594 * @param profile If the device owner is set, any profile is allowed.
12595 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012596 * @param preferences the list of profile network preferences for the
12597 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090012598 * @param listener an optional listener to listen for completion of the operation.
12599 */
12600 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012601 public void setProfileNetworkPreferences(
12602 @NonNull final UserHandle profile,
12603 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090012604 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012605 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012606 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012607
12608 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012609 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
12610 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
12611 .build();
12612 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012613 }
12614
paulhu3ffffe72021-09-16 10:15:22 +080012615 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012616 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012617 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012618 }
12619 if (profile.getIdentifier() < 0) {
12620 throw new IllegalArgumentException("Must explicitly specify a user handle ("
12621 + "UserHandle.CURRENT not supported)");
12622 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070012623 if (!isNetworkPreferenceAllowedForProfile(profile)) {
12624 throw new IllegalArgumentException("Profile must be a managed profile "
12625 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012626 }
paulhuaa0743d2021-05-26 21:56:03 +080012627
Chalard Jean0606fc82022-12-14 20:34:43 +090012628 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012629 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012630 for (final ProfileNetworkPreference preference : preferences) {
12631 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012632 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080012633 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012634 switch (preference.getPreference()) {
12635 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
12636 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012637 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012638 if (preference.getPreferenceEnterpriseId() != 0) {
12639 throw new IllegalArgumentException(
12640 "Invalid enterprise identifier in setProfileNetworkPreferences");
12641 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012642 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080012643 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
12644 blockingNonEnterprise = true;
12645 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012646 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
12647 allowFallback = false;
12648 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012649 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012650 // This code is needed even though there is a check later on,
12651 // because isRangeAlreadyInPreferenceList assumes that every preference
12652 // has a UID list.
12653 if (hasDefaultPreference) {
12654 throw new IllegalArgumentException(
12655 "Default profile preference should not be set along with other "
12656 + "preference");
12657 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012658 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
12659 throw new IllegalArgumentException(
12660 "Invalid enterprise identifier in setProfileNetworkPreferences");
12661 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012662 final Set<UidRange> uidRangeSet =
12663 getUidListToBeAppliedForNetworkPreference(profile, preference);
12664 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
12665 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
12666 } else {
12667 throw new IllegalArgumentException(
12668 "Overlapping uid range in setProfileNetworkPreferences");
12669 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012670 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012671 nc.addEnterpriseId(
12672 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012673 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
12674 break;
12675 default:
12676 throw new IllegalArgumentException(
12677 "Invalid preference in setProfileNetworkPreferences");
12678 }
Junyu Lai35665cc2022-12-19 17:37:48 +080012679 preferenceList.add(new ProfileNetworkPreferenceInfo(
12680 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070012681 if (hasDefaultPreference && preferenceList.size() > 1) {
12682 throw new IllegalArgumentException(
12683 "Default profile preference should not be set along with other preference");
12684 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012685 }
12686 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012687 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012688 }
12689
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012690 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
12691 @NonNull final UserHandle profile,
12692 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
12693 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080012694 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
12695 profileNetworkPreference.getIncludedUids());
12696
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012697 if (uidRangeSet.size() > 0) {
12698 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
12699 throw new IllegalArgumentException(
12700 "Allow uid range is outside the uid range of profile.");
12701 }
12702 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080012703 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012704 profileNetworkPreference.getExcludedUids());
12705 if (disallowUidRangeSet.size() > 0) {
12706 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
12707 throw new IllegalArgumentException(
12708 "disallow uid range is outside the uid range of profile.");
12709 }
12710 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
12711 disallowUidRangeSet);
12712 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012713 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012714 uidRangeSet.add(profileUids);
12715 }
12716 }
12717 return uidRangeSet;
12718 }
12719
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012720 private boolean isEnterpriseIdentifierValid(
12721 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090012722 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080012723 return true;
12724 }
12725 return false;
12726 }
12727
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012728 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090012729 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012730 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090012731 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012732 // The NRI for a user should contain the request for capabilities.
12733 // If fallback to default network is needed then NRI should include
12734 // the request for the default network. Create an image of it to
12735 // have the correct UIDs in it (also a request can only be part of one NRI, because
12736 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012737 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
12738 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080012739 if (pref.allowFallback) {
12740 nrs.add(createDefaultInternetRequestForTransport(
12741 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12742 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012743 if (VDBG) {
12744 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
12745 pref.capabilities.getUids()));
12746 }
12747
Chiachang Wang8156c4e2021-03-19 00:45:39 +000012748 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080012749 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080012750 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012751 result.add(nri);
12752 }
12753 return result;
12754 }
12755
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012756 /**
12757 * Compare if the given UID range sets have the same UIDs.
12758 *
12759 */
12760 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090012761 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012762 @NonNull Set<UidRange> uidRangeSet) {
12763 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
12764 return false;
12765 }
Chalard Jean0606fc82022-12-14 20:34:43 +090012766 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080012767 if (UidRangeUtils.doesRangeSetOverlap(
12768 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
12769 return true;
12770 }
12771 }
12772 return false;
12773 }
12774
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012775 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090012776 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012777 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012778 /*
12779 * handleSetProfileNetworkPreference is always called for single user.
12780 * preferenceList only contains preferences for different uids within the same user
12781 * (enforced by getUidListToBeAppliedForNetworkPreference).
12782 * Clear all the existing preferences for the user before applying new preferences.
12783 *
12784 */
Chalard Jean0606fc82022-12-14 20:34:43 +090012785 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
12786 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080012787 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
12788 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070012789
paulhu74128522021-09-28 02:29:03 +000012790 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
12791 addPerAppDefaultNetworkRequests(
12792 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080012793 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080012794
Chalard Jeanb5a139f2021-02-25 21:46:34 +090012795 // Finally, rematch.
12796 rematchAllNetworksAndRequests();
12797
12798 if (null != listener) {
12799 try {
12800 listener.onComplete();
12801 } catch (RemoteException e) {
12802 loge("Listener for setProfileNetworkPreference has died");
12803 }
12804 }
12805 }
12806
paulhu51f77dc2021-06-07 02:34:20 +000012807 @VisibleForTesting
12808 @NonNull
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012809 ArraySet<NetworkRequestInfo> createNrisForPreferenceOrder(@NonNull final Set<Integer> uids,
12810 @NonNull final List<NetworkRequest> requests,
12811 final int preferenceOrder) {
paulhu51f77dc2021-06-07 02:34:20 +000012812 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12813 if (uids.size() == 0) {
12814 // Should not create NetworkRequestInfo if no preferences. Without uid range in
12815 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
paulhu51f77dc2021-06-07 02:34:20 +000012816 return nris;
12817 }
12818
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012819 final Set<UidRange> ranges = new ArraySet<>();
12820 for (final int uid : uids) {
12821 ranges.add(new UidRange(uid, uid));
12822 }
12823 setNetworkRequestUids(requests, ranges);
12824 nris.add(new NetworkRequestInfo(Process.myUid(), requests, preferenceOrder));
12825 return nris;
12826 }
12827
12828 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
12829 @NonNull final Set<Integer> uids) {
paulhu51f77dc2021-06-07 02:34:20 +000012830 final List<NetworkRequest> requests = new ArrayList<>();
12831 // The NRI should be comprised of two layers:
12832 // - The request for the mobile network preferred.
12833 // - The request for the default network, for fallback.
12834 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090012835 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000012836 requests.add(createDefaultInternetRequestForTransport(
12837 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012838 return createNrisForPreferenceOrder(uids, requests, PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED
12839 );
12840 }
12841
12842 ArraySet<NetworkRequestInfo> createMultiLayerNrisFromSatelliteNetworkFallbackUids(
12843 @NonNull final Set<Integer> uids) {
12844 final List<NetworkRequest> requests = new ArrayList<>();
12845
12846 // request: track default(unrestricted internet network)
12847 requests.add(createDefaultInternetRequestForTransport(
12848 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
12849
12850 // request: restricted Satellite internet
12851 final NetworkCapabilities cap = new NetworkCapabilities.Builder()
12852 .addCapability(NET_CAPABILITY_INTERNET)
12853 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
12854 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED)
12855 .addTransportType(NetworkCapabilities.TRANSPORT_SATELLITE)
12856 .build();
12857 requests.add(createNetworkRequest(NetworkRequest.Type.REQUEST, cap));
12858
12859 return createNrisForPreferenceOrder(uids, requests, PREFERENCE_ORDER_SATELLITE_FALLBACK);
paulhu51f77dc2021-06-07 02:34:20 +000012860 }
12861
12862 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000012863 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000012864 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
12865 addPerAppDefaultNetworkRequests(
12866 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000012867 // Finally, rematch.
12868 rematchAllNetworksAndRequests();
12869 }
12870
Nagendra Prasad Nagarle Basavaraju804aa232024-01-31 15:35:31 +000012871 private void handleSetSatelliteNetworkPreference(
12872 @NonNull final Set<Integer> satelliteNetworkPreferredUids) {
12873 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_SATELLITE_FALLBACK);
12874 addPerAppDefaultNetworkRequests(
12875 createMultiLayerNrisFromSatelliteNetworkFallbackUids(satelliteNetworkPreferredUids)
12876 );
12877 // Finally, rematch.
12878 rematchAllNetworksAndRequests();
12879 }
12880
Patrick Rohr2857ac42022-01-21 14:58:16 +010012881 private void handleIngressRateLimitChanged() {
12882 final long oldIngressRateLimit = mIngressRateLimit;
12883 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
12884 mContext);
12885 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
12886 if (canNetworkBeRateLimited(networkAgent)) {
12887 // If rate limit has previously been enabled, remove the old limit first.
12888 if (oldIngressRateLimit >= 0) {
12889 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
12890 }
12891 if (mIngressRateLimit >= 0) {
12892 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
12893 mIngressRateLimit);
12894 }
12895 }
12896 }
12897 }
12898
12899 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012900 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
Chalard Jeandf29a852023-05-29 17:02:43 +090012901 if (!mDeps.isAtLeastT()) return false;
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090012902
Patrick Rohrff3b3f82022-02-09 15:15:52 +010012903 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
12904 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
12905 // internet connectivity can be rate limited.
12906 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
12907 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010012908 return false;
12909 }
12910
12911 final String iface = networkAgent.linkProperties.getInterfaceName();
12912 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010012913 // This may happen in tests, but if there is no interface then there is nothing that
12914 // can be rate limited.
12915 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010012916 return false;
12917 }
12918 return true;
12919 }
12920
James Mattis45d81842021-01-10 14:24:24 -080012921 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080012922 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
12923 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080012924 }
12925
12926 /**
12927 * Used by automotive devices to set the network preferences used to direct traffic at an
12928 * application level as per the given OemNetworkPreferences. An example use-case would be an
12929 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
12930 * vehicle via a particular network.
12931 *
12932 * Calling this will overwrite the existing preference.
12933 *
James Mattisda32cfe2021-01-26 16:23:52 -080012934 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090012935 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080012936 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080012937 */
James Mattis47db0582021-01-01 14:13:35 -080012938 @Override
James Mattis45d81842021-01-10 14:24:24 -080012939 public void setOemNetworkPreference(
12940 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090012941 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080012942
James Mattisfa270db2021-05-31 17:11:10 -070012943 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
12944 // Only bypass the permission/device checks if this is a valid test request.
12945 if (isValidTestOemNetworkPreference(preference)) {
12946 enforceManageTestNetworksPermission();
12947 } else {
12948 enforceAutomotiveDevice();
12949 enforceOemNetworkPreferencesPermission();
12950 validateOemNetworkPreferences(preference);
12951 }
James Mattis45d81842021-01-10 14:24:24 -080012952
James Mattis45d81842021-01-10 14:24:24 -080012953 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
12954 new Pair<>(preference, listener)));
12955 }
12956
James Mattisfa270db2021-05-31 17:11:10 -070012957 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000012958 * Sets the specified UIDs to get/receive the VPN as the only default network.
12959 *
12960 * Calling this will overwrite the existing network preference for this session, and the
12961 * specified UIDs won't get any default network when no VPN is connected.
12962 *
12963 * @param session The VPN session which manages the passed UIDs.
12964 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
12965 * setting for this session if the array is empty. Null is not allowed, the
12966 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
12967 * @hide
12968 */
12969 @Override
12970 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
12971 Objects.requireNonNull(ranges);
12972 enforceNetworkStackOrSettingsPermission();
12973 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
12974 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
12975 throw new IllegalArgumentException(
12976 "setVpnNetworkPreference: Passed UID ranges overlap");
12977 }
12978
12979 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
12980 new VpnNetworkPreferenceInfo(session,
12981 new ArraySet<UidRange>(Arrays.asList(ranges)))));
12982 }
12983
12984 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
12985 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
12986
12987 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
12988 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
12989
12990 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
12991 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
12992 // Finally, rematch.
12993 rematchAllNetworksAndRequests();
12994 }
12995
12996 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
12997 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
12998 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
12999 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
13000 final List<NetworkRequest> requests = new ArrayList<>();
13001 // Request VPN only, so other networks won't be the fallback options when VPN is not
13002 // connected temporarily.
13003 requests.add(createVpnRequest());
13004 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
13005 setNetworkRequestUids(requests, uidRanges);
13006 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
13007 }
13008 return nris;
13009 }
13010
13011 /**
James Mattisfa270db2021-05-31 17:11:10 -070013012 * Check the validity of an OEM network preference to be used for testing purposes.
13013 * @param preference the preference to validate
13014 * @return true if this is a valid OEM network preference test request.
13015 */
13016 private boolean isValidTestOemNetworkPreference(
13017 @NonNull final OemNetworkPreferences preference) {
13018 // Allow for clearing of an existing OemNetworkPreference used for testing.
13019 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
13020 // changes after this check is complete. This is an unlikely scenario as calling of this API
13021 // is controlled by the OEM therefore the added complexity is not worth adding given those
13022 // circumstances. That said, it is an edge case to be aware of hence this comment.
13023 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
13024 && isTestOemNetworkPreference(mOemNetworkPreferences);
13025 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
13026 }
13027
13028 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
13029 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
13030 return prefMap.size() == 1
13031 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
13032 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
13033 }
13034
James Mattis45d81842021-01-10 14:24:24 -080013035 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
13036 for (@OemNetworkPreferences.OemNetworkPreference final int pref
13037 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070013038 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
13039 throw new IllegalArgumentException(
13040 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
13041 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080013042 }
13043 }
13044 }
13045
13046 private void handleSetOemNetworkPreference(
13047 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090013048 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080013049 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
13050 if (DBG) {
13051 log("set OEM network preferences :" + preference.toString());
13052 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090013053
James Mattiscb1e0362021-04-06 17:07:42 -070013054 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000013055 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
13056 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
13057 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080013058 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080013059
13060 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090013061 try {
13062 listener.onComplete();
13063 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080013064 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090013065 }
James Mattis45d81842021-01-10 14:24:24 -080013066 }
13067 }
13068
paulhu74128522021-09-28 02:29:03 +000013069 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080013070 // Skip the requests which are set by other network preference. Because the uid range rules
13071 // should stay in netd.
13072 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080013073 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080013074 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080013075 }
13076
James Mattis3ce3d3c2021-02-09 18:18:28 -080013077 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
13078 ensureRunningOnConnectivityServiceThread();
13079 mDefaultNetworkRequests.addAll(nris);
13080 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
13081 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080013082 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000013083 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
13084 nrisToRegister.addAll(
13085 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
13086 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013087 }
13088
13089 /**
13090 * All current requests that are tracking the default network need to be assessed as to whether
13091 * or not the current set of per-application default requests will be changing their default
13092 * network. If so, those requests will need to be updated so that they will send callbacks for
13093 * default network changes at the appropriate time. Additionally, those requests tracking the
13094 * default that were previously updated by this flow will need to be reassessed.
13095 * @return the nris which will need to be updated.
13096 */
13097 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
13098 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
13099 // Get the distinct nris to check since for multilayer requests, it is possible to have the
13100 // same nri in the map's values for each of its NetworkRequest objects.
13101 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080013102 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013103 // Include this nri if it is currently being tracked.
13104 if (isPerAppTrackedNri(nri)) {
13105 defaultCallbackRequests.add(nri);
13106 continue;
13107 }
13108 // We only track callbacks for requests tracking the default.
13109 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
13110 continue;
13111 }
13112 // Include this nri if it will be tracked by the new per-app default requests.
13113 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013114 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080013115 if (isNriGoingToBeTracked) {
13116 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080013117 }
13118 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080013119 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080013120 }
13121
James Mattis3ce3d3c2021-02-09 18:18:28 -080013122 /**
13123 * Create nris for those network requests that are currently tracking the default network that
13124 * are being controlled by a per-application default.
13125 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
13126 * foundation when creating the nri. Important items include the calling uid's original
13127 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
13128 * requests are assumed to have already been validated as needing to be updated.
13129 * @return the Set of nris to use when registering network requests.
13130 */
13131 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
13132 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
13133 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
13134 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
13135 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013136 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013137
Chalard Jean9473c982021-07-29 20:03:04 +090013138 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080013139 if (trackingNri == mDefaultRequest) {
13140 callbackRequestsToRegister.add(new NetworkRequestInfo(
13141 callbackRequest,
13142 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
13143 continue;
13144 }
13145
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013146 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080013147 callbackRequestsToRegister.add(new NetworkRequestInfo(
13148 callbackRequest,
13149 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090013150 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090013151 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080013152 }
13153 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080013154 }
13155
Chalard Jean17215832021-03-01 14:06:28 +090013156 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
13157 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090013158 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000013159 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090013160 }
13161 }
13162
James Mattis45d81842021-01-10 14:24:24 -080013163 /**
13164 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
13165 */
13166 @VisibleForTesting
13167 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013168 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080013169 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080013170 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080013171 final SparseArray<Set<Integer>> uids =
13172 createUidsFromOemNetworkPreferences(preference);
13173 for (int i = 0; i < uids.size(); i++) {
13174 final int key = uids.keyAt(i);
13175 final Set<Integer> value = uids.valueAt(i);
13176 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
13177 // No need to add an nri without any requests.
13178 if (0 == nri.mRequests.size()) {
13179 continue;
13180 }
13181 nris.add(nri);
13182 }
13183
13184 return nris;
13185 }
13186
13187 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
13188 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070013189 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080013190 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080013191 final List<UserHandle> users =
13192 mContext.getSystemService(UserManager.class).getUserHandles(true);
13193 if (null == users || users.size() == 0) {
13194 if (VDBG || DDBG) {
13195 log("No users currently available for setting the OEM network preference.");
13196 }
James Mattisb6b6a432021-06-01 22:30:36 -070013197 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080013198 }
James Mattis45d81842021-01-10 14:24:24 -080013199 for (final Map.Entry<String, Integer> entry :
13200 preference.getNetworkPreferences().entrySet()) {
13201 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070013202 // Add the rules for all users as this policy is device wide.
13203 for (final UserHandle user : users) {
13204 try {
13205 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
13206 if (!prefToUids.contains(pref)) {
13207 prefToUids.put(pref, new ArraySet<>());
13208 }
13209 prefToUids.get(pref).add(uid);
13210 } catch (PackageManager.NameNotFoundException e) {
13211 // Although this may seem like an error scenario, it is ok that uninstalled
13212 // packages are sent on a network preference as the system will watch for
13213 // package installations associated with this network preference and update
13214 // accordingly. This is done to minimize race conditions on app install.
13215 continue;
James Mattis45d81842021-01-10 14:24:24 -080013216 }
James Mattis45d81842021-01-10 14:24:24 -080013217 }
13218 }
James Mattisb6b6a432021-06-01 22:30:36 -070013219 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080013220 }
13221
13222 private NetworkRequestInfo createNriFromOemNetworkPreferences(
13223 @OemNetworkPreferences.OemNetworkPreference final int preference,
13224 @NonNull final Set<Integer> uids) {
13225 final List<NetworkRequest> requests = new ArrayList<>();
13226 // Requests will ultimately be evaluated by order of insertion therefore it matters.
13227 switch (preference) {
13228 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
13229 requests.add(createUnmeteredNetworkRequest());
13230 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070013231 requests.add(createDefaultInternetRequestForTransport(
13232 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080013233 break;
13234 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
13235 requests.add(createUnmeteredNetworkRequest());
13236 requests.add(createOemPaidNetworkRequest());
13237 break;
13238 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
13239 requests.add(createOemPaidNetworkRequest());
13240 break;
13241 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
13242 requests.add(createOemPrivateNetworkRequest());
13243 break;
James Mattisfa270db2021-05-31 17:11:10 -070013244 case OEM_NETWORK_PREFERENCE_TEST:
13245 requests.add(createUnmeteredNetworkRequest());
13246 requests.add(createTestNetworkRequest());
13247 requests.add(createDefaultRequest());
13248 break;
13249 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
13250 requests.add(createTestNetworkRequest());
13251 break;
James Mattis45d81842021-01-10 14:24:24 -080013252 default:
13253 // This should never happen.
13254 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
13255 + " called with invalid preference of " + preference);
13256 }
13257
James Mattisfa270db2021-05-31 17:11:10 -070013258 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090013259 for (final int uid : uids) {
13260 ranges.add(new UidRange(uid, uid));
13261 }
13262 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080013263 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080013264 }
13265
13266 private NetworkRequest createUnmeteredNetworkRequest() {
13267 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13268 .addCapability(NET_CAPABILITY_NOT_METERED)
13269 .addCapability(NET_CAPABILITY_VALIDATED);
13270 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
13271 }
13272
13273 private NetworkRequest createOemPaidNetworkRequest() {
13274 // NET_CAPABILITY_OEM_PAID is a restricted capability.
13275 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13276 .addCapability(NET_CAPABILITY_OEM_PAID)
13277 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13278 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13279 }
13280
13281 private NetworkRequest createOemPrivateNetworkRequest() {
13282 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
13283 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
13284 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
13285 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
13286 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
13287 }
13288
13289 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070013290 final NetworkCapabilities netcap = new NetworkCapabilities();
13291 netcap.addCapability(NET_CAPABILITY_INTERNET);
13292 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
13293 return netcap;
13294 }
13295
13296 private NetworkRequest createTestNetworkRequest() {
13297 final NetworkCapabilities netcap = new NetworkCapabilities();
13298 netcap.clearAll();
13299 netcap.addTransportType(TRANSPORT_TEST);
13300 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080013301 }
James Mattis47db0582021-01-01 14:13:35 -080013302 }
markchien738ad912021-12-09 18:15:45 +080013303
Junyu Lai38c75032023-12-04 07:52:19 +000013304 @RequiresApi(Build.VERSION_CODES.TIRAMISU)
markchien738ad912021-12-09 18:15:45 +080013305 @Override
Junyu Laidf210362023-10-24 02:47:50 +000013306 public void setDataSaverEnabled(final boolean enable) {
13307 enforceNetworkStackOrSettingsPermission();
13308 try {
13309 final boolean ret = mNetd.bandwidthEnableDataSaver(enable);
13310 if (!ret) {
13311 throw new IllegalStateException("Error when changing iptables: " + enable);
13312 }
13313 } catch (RemoteException e) {
13314 // Lack of permission or binder errors.
13315 throw new IllegalStateException(e);
13316 }
Ken Chen24330172023-10-20 13:02:14 +080013317
13318 try {
13319 mBpfNetMaps.setDataSaverEnabled(enable);
13320 } catch (ServiceSpecificException | UnsupportedOperationException e) {
13321 Log.e(TAG, "Failed to set data saver " + enable + " : " + e);
13322 }
Junyu Laidf210362023-10-24 02:47:50 +000013323 }
13324
13325 @Override
markchien738ad912021-12-09 18:15:45 +080013326 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
13327 enforceNetworkStackOrSettingsPermission();
13328
13329 try {
13330 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013331 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013332 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013333 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080013334 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013335 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013336 throw new IllegalStateException(e);
13337 }
13338 }
13339
13340 @Override
13341 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
13342 enforceNetworkStackOrSettingsPermission();
13343
13344 try {
13345 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013346 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013347 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013348 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080013349 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013350 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080013351 throw new IllegalStateException(e);
13352 }
13353 }
markchiene1561fa2021-12-09 22:00:56 +080013354
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013355 private int setPackageFirewallRule(final int chain, final String packageName, final int rule)
13356 throws PackageManager.NameNotFoundException {
13357 final PackageManager pm = mContext.getPackageManager();
13358 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13359 if (appId < Process.FIRST_APPLICATION_UID) {
13360 throw new RuntimeException("Can't set package firewall rule for system app "
13361 + packageName + " with appId " + appId);
13362 }
13363 for (final UserHandle uh : mUserManager.getUserHandles(false /* excludeDying */)) {
13364 final int uid = uh.getUid(appId);
13365 setUidFirewallRule(chain, uid, rule);
13366 }
13367 return appId;
13368 }
13369
markchiene1561fa2021-12-09 22:00:56 +080013370 @Override
markchien3c04e662022-03-22 16:29:56 +080013371 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080013372 enforceNetworkStackOrSettingsPermission();
13373
markchien3c04e662022-03-22 16:29:56 +080013374 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
13375 int firewallRule = getFirewallRuleType(chain, rule);
13376
13377 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
13378 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
13379 }
13380
markchiene1561fa2021-12-09 22:00:56 +080013381 try {
markchien3c04e662022-03-22 16:29:56 +080013382 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013383 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080013384 throw new IllegalStateException(e);
13385 }
13386 }
markchien98a6f952022-01-13 23:43:53 +080013387
Chalard Jeanc8fefb32023-09-05 21:41:13 +090013388 private int getPackageFirewallRule(final int chain, final String packageName)
13389 throws PackageManager.NameNotFoundException {
13390 final PackageManager pm = mContext.getPackageManager();
13391 final int appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0 /* flags */));
13392 return getUidFirewallRule(chain, appId);
13393 }
13394
Motomu Utsumi900b8062023-01-19 16:16:49 +090013395 @Override
13396 public int getUidFirewallRule(final int chain, final int uid) {
13397 enforceNetworkStackOrSettingsPermission();
13398 return mBpfNetMaps.getUidRule(chain, uid);
13399 }
13400
markchien3c04e662022-03-22 16:29:56 +080013401 private int getFirewallRuleType(int chain, int rule) {
13402 final int defaultRule;
13403 switch (chain) {
13404 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000013405 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
13406 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000013407 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080013408 defaultRule = FIREWALL_RULE_ALLOW;
13409 break;
13410 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
13411 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
13412 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
13413 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
Suprabh Shukla2d893b62023-11-06 08:47:40 -080013414 case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
markchien3c04e662022-03-22 16:29:56 +080013415 defaultRule = FIREWALL_RULE_DENY;
13416 break;
13417 default:
13418 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
13419 }
13420 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
13421
13422 return rule;
13423 }
13424
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013425 private void closeSocketsForFirewallChainLocked(final int chain)
13426 throws ErrnoException, SocketException, InterruptedIOException {
Junyu Laie0031522023-08-29 18:32:57 +080013427 if (BpfNetMapsUtils.isFirewallAllowList(chain)) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013428 // Allowlist means the firewall denies all by default, uids must be explicitly allowed
13429 // So, close all non-system socket owned by uids that are not explicitly allowed
13430 Set<Range<Integer>> ranges = new ArraySet<>();
13431 ranges.add(new Range<>(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE));
13432 final Set<Integer> exemptUids = mBpfNetMaps.getUidsWithAllowRuleOnAllowListChain(chain);
13433 mDeps.destroyLiveTcpSockets(ranges, exemptUids);
13434 } else {
13435 // Denylist means the firewall allows all by default, uids must be explicitly denied
13436 // So, close socket owned by uids that are explicitly denied
13437 final Set<Integer> ownerUids = mBpfNetMaps.getUidsWithDenyRuleOnDenyListChain(chain);
13438 mDeps.destroyLiveTcpSocketsByOwnerUids(ownerUids);
13439 }
13440 }
13441
markchien98a6f952022-01-13 23:43:53 +080013442 @Override
13443 public void setFirewallChainEnabled(final int chain, final boolean enable) {
13444 enforceNetworkStackOrSettingsPermission();
13445
13446 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080013447 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090013448 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080013449 throw new IllegalStateException(e);
13450 }
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013451
Chalard Jeandf29a852023-05-29 17:02:43 +090013452 if (mDeps.isAtLeastU() && enable) {
Motomu Utsumid44a33a2023-03-28 18:08:12 +090013453 try {
13454 closeSocketsForFirewallChainLocked(chain);
13455 } catch (ErrnoException | SocketException | InterruptedIOException e) {
13456 Log.e(TAG, "Failed to close sockets after enabling chain (" + chain + "): " + e);
13457 }
13458 }
markchien98a6f952022-01-13 23:43:53 +080013459 }
13460
markchien00a0bed2022-01-13 23:46:13 +080013461 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013462 public boolean getFirewallChainEnabled(final int chain) {
13463 enforceNetworkStackOrSettingsPermission();
13464
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000013465 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000013466 }
13467
13468 @Override
markchien00a0bed2022-01-13 23:46:13 +080013469 public void replaceFirewallChain(final int chain, final int[] uids) {
13470 enforceNetworkStackOrSettingsPermission();
13471
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000013472 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080013473 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080013474
13475 @Override
13476 public IBinder getCompanionDeviceManagerProxyService() {
13477 enforceNetworkStackPermission(mContext);
13478 return mCdmps;
13479 }
Chalard Jean2fb66f12023-08-25 12:50:37 +090013480
13481 @Override
13482 public IBinder getRoutingCoordinatorService() {
13483 enforceNetworkStackPermission(mContext);
13484 return mRoutingCoordinatorService;
13485 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070013486}