blob: b449e72bd0769ea703d076deb57cf89a005d8481 [file] [log] [blame]
The Android Open Source Project28527d22009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
Remi NGUYEN VAN028cb1b2021-05-12 14:15:24 +000018
Haoyu Baib5da5752012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090020import static android.content.pm.PackageManager.FEATURE_BLUETOOTH;
21import static android.content.pm.PackageManager.FEATURE_WATCH;
22import static android.content.pm.PackageManager.FEATURE_WIFI;
23import static android.content.pm.PackageManager.FEATURE_WIFI_DIRECT;
Chalard Jean9a396cc2018-02-21 18:43:54 +090024import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +090025import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_ATTEMPTED_BITMASK;
26import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_PROBES_SUCCEEDED_BITMASK;
27import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport.KEY_NETWORK_VALIDATION_RESULT;
28import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_DNS_EVENTS;
29import static android.net.ConnectivityDiagnosticsManager.DataStallReport.DETECTION_METHOD_TCP_METRICS;
30import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_DNS_CONSECUTIVE_TIMEOUTS;
31import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS;
32import static android.net.ConnectivityDiagnosticsManager.DataStallReport.KEY_TCP_PACKET_FAIL_RATE;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +090033import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_MASK;
34import static android.net.ConnectivityManager.BLOCKED_REASON_LOCKDOWN_VPN;
Sudheer Shanka98215562021-03-23 08:12:28 +000035import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
Jeff Sharkey971cd162011-08-29 16:02:57 -070036import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
markchien3c04e662022-03-22 16:29:56 +080037import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
38import static android.net.ConnectivityManager.FIREWALL_RULE_DEFAULT;
39import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090040import static android.net.ConnectivityManager.TYPE_BLUETOOTH;
Lorenzo Colitti23e9afc2017-08-24 22:35:10 +090041import static android.net.ConnectivityManager.TYPE_ETHERNET;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090042import static android.net.ConnectivityManager.TYPE_MOBILE;
43import static android.net.ConnectivityManager.TYPE_MOBILE_CBS;
44import static android.net.ConnectivityManager.TYPE_MOBILE_DUN;
45import static android.net.ConnectivityManager.TYPE_MOBILE_EMERGENCY;
46import static android.net.ConnectivityManager.TYPE_MOBILE_FOTA;
47import static android.net.ConnectivityManager.TYPE_MOBILE_HIPRI;
48import static android.net.ConnectivityManager.TYPE_MOBILE_IA;
49import static android.net.ConnectivityManager.TYPE_MOBILE_IMS;
50import static android.net.ConnectivityManager.TYPE_MOBILE_MMS;
51import static android.net.ConnectivityManager.TYPE_MOBILE_SUPL;
Robert Greenwaltbe46b752014-05-13 21:41:06 -070052import static android.net.ConnectivityManager.TYPE_NONE;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090053import static android.net.ConnectivityManager.TYPE_PROXY;
Sreeram Ramachandrane8cb66e2014-10-30 14:55:29 -070054import static android.net.ConnectivityManager.TYPE_VPN;
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090055import static android.net.ConnectivityManager.TYPE_WIFI;
56import static android.net.ConnectivityManager.TYPE_WIFI_P2P;
Jeff Sharkey6b9021d2012-07-26 18:32:30 -070057import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkey921ebf22011-05-19 17:12:49 -070058import static android.net.ConnectivityManager.isNetworkTypeValid;
lucaslinb1ff1b22021-04-23 21:03:39 +080059import static android.net.ConnectivitySettingsManager.PRIVATE_DNS_MODE_OPPORTUNISTIC;
lucasline117e2e2019-10-22 18:27:33 +080060import static android.net.INetworkMonitor.NETWORK_VALIDATION_PROBE_PRIVDNS;
Chiachang Wangeff18972019-05-23 16:29:30 +080061import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_PARTIAL;
Cody Kestingf1120be2020-08-03 18:01:40 -070062import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_SKIPPED;
Chiachang Wangeff18972019-05-23 16:29:30 +080063import static android.net.INetworkMonitor.NETWORK_VALIDATION_RESULT_VALID;
Paul Jensen53f08952015-06-16 14:27:36 -040064import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Chalard Jeanb5a139f2021-02-25 21:46:34 +090065import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
Lorenzo Colitti0f042202016-07-18 18:40:42 +090066import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090067import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
Lorenzo Colitticda101b2020-11-24 21:45:25 +090068import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_CONGESTED;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090069import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
70import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey07e19362017-10-27 17:22:59 -060071import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeana23bc9e2018-01-30 22:41:41 +090072import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
junyulai719814c2021-01-13 18:13:11 +080073import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +090074import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
James Mattis45d81842021-01-10 14:24:24 -080075import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
76import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
lucaslin2240ef62019-03-12 13:08:03 +080077import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
Lorenzo Colittie14a6222015-05-14 17:07:20 +090078import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080079import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
80import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
Roshan Pius98f59ec2021-02-23 08:47:39 -080081import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
82import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
83import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
Chalard Jeand61375d2020-01-14 22:46:36 +090084import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Chalard Jean5b639762020-03-09 21:25:37 +090085import static android.net.NetworkCapabilities.TRANSPORT_TEST;
Jeff Sharkey07e19362017-10-27 17:22:59 -060086import static android.net.NetworkCapabilities.TRANSPORT_VPN;
Cody Kesting7474f672021-05-11 14:22:40 -070087import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
junyulai1b1c8742021-03-12 20:05:08 +080088import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
Chalard Jean0702f982021-09-16 21:50:07 +090089import static android.net.NetworkScore.POLICY_TRANSPORT_PRIMARY;
James Mattisfa270db2021-05-31 17:11:10 -070090import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST;
91import static android.net.OemNetworkPreferences.OEM_NETWORK_PREFERENCE_TEST_ONLY;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070092import static android.os.Process.INVALID_UID;
Ken Chen5e65a852020-12-24 12:59:10 +080093import static android.os.Process.VPN_UID;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090094import static android.provider.DeviceConfig.NAMESPACE_CONNECTIVITY;
Patrick Rohr2857ac42022-01-21 14:58:16 +010095import static android.system.OsConstants.ETH_P_ALL;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070096import static android.system.OsConstants.IPPROTO_TCP;
97import static android.system.OsConstants.IPPROTO_UDP;
Jeff Sharkey07e19362017-10-27 17:22:59 -060098
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +090099import static com.android.net.module.util.DeviceConfigUtils.TETHERING_MODULE_NAME;
Xiao Ma60142372022-07-16 17:30:20 +0900100import static com.android.net.module.util.NetworkMonitorUtils.isPrivateDnsValidationRequired;
Junyu Lai4c6fe232023-04-11 11:33:46 +0800101import static com.android.net.module.util.PermissionUtils.checkAnyPermissionOf;
paulhu3ffffe72021-09-16 10:15:22 +0800102import static com.android.net.module.util.PermissionUtils.enforceAnyPermissionOf;
103import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermission;
104import static com.android.net.module.util.PermissionUtils.enforceNetworkStackPermissionOr;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900105
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800106import static java.util.Map.Entry;
107
Chalard Jean5b639762020-03-09 21:25:37 +0900108import android.Manifest;
Lorenzo Colittibad9d912019-04-12 10:48:06 +0000109import android.annotation.NonNull;
Wenchao Tonge164e002015-03-04 13:26:38 -0800110import android.annotation.Nullable;
Michael Groover73f69482023-01-27 11:01:25 -0600111import android.annotation.SuppressLint;
Chiachang Wang3bc52762021-11-25 14:17:57 +0800112import android.annotation.TargetApi;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800113import android.app.AppOpsManager;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800114import android.app.BroadcastOptions;
Wink Saville32506bc2013-06-29 21:10:57 -0700115import android.app.PendingIntent;
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -0700116import android.app.admin.DevicePolicyManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900117import android.app.compat.CompatChanges;
junyulaie7c7d2a2021-01-26 15:29:15 +0800118import android.app.usage.NetworkStatsManager;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700119import android.content.BroadcastReceiver;
paulhu7746e4e2020-06-09 19:07:03 +0800120import android.content.ComponentName;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800121import android.content.ContentResolver;
122import android.content.Context;
123import android.content.Intent;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700124import android.content.IntentFilter;
markchien9eb93992020-03-27 18:12:39 +0800125import android.content.pm.PackageManager;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900126import android.content.res.XmlResourceParser;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700127import android.database.ContentObserver;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900128import android.net.CaptivePortal;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900129import android.net.CaptivePortalData;
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -0700130import android.net.ConnectionInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800131import android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Cody Kestingb12ad4c2020-01-06 16:55:35 -0800132import android.net.ConnectivityDiagnosticsManager.DataStallReport;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800133import android.net.ConnectivityManager;
Lorenzo Colitti79c6f222021-03-18 00:54:57 +0900134import android.net.ConnectivityManager.BlockedReason;
Roshan Pius951c0032020-12-22 15:10:42 -0800135import android.net.ConnectivityManager.NetworkCallback;
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +0900136import android.net.ConnectivityManager.RestrictBackgroundStatus;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900137import android.net.ConnectivityResources;
paulhu90a7a512021-03-17 17:19:09 +0800138import android.net.ConnectivitySettingsManager;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900139import android.net.DataStallReportParcelable;
paulhua10d8212020-11-10 15:32:56 +0800140import android.net.DnsResolverServiceManager;
Tyler Wear72388212021-09-09 14:49:02 -0700141import android.net.DscpPolicy;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +0900142import android.net.ICaptivePortal;
Cody Kestingd199a9d2019-12-17 12:55:28 -0800143import android.net.IConnectivityDiagnosticsCallback;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800144import android.net.IConnectivityManager;
Luke Huang81413192019-03-16 00:31:46 +0800145import android.net.IDnsResolver;
Luke Huang46289a22018-09-27 19:33:11 +0800146import android.net.INetd;
Chiachang Wang6a7d31e2021-02-04 17:29:59 +0800147import android.net.INetworkActivityListener;
Remi NGUYEN VAN73f96a22021-02-19 12:53:54 +0900148import android.net.INetworkAgent;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900149import android.net.INetworkMonitor;
150import android.net.INetworkMonitorCallbacks;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900151import android.net.INetworkOfferCallback;
Chalard Jeanfa45a682021-02-25 17:23:40 +0900152import android.net.IOnCompleteListener;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700153import android.net.IQosCallback;
junyulai070f9ff2019-01-16 20:23:34 +0800154import android.net.ISocketKeepaliveCallback;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900155import android.net.InetAddresses;
Xiao Ma555e4082019-04-10 19:01:52 +0900156import android.net.IpMemoryStore;
Lorenzo Colittif7e17392019-01-08 10:04:25 +0900157import android.net.IpPrefix;
Jaikumar Ganesh0db51a02010-12-21 22:31:44 -0800158import android.net.LinkProperties;
Charles He9369e612017-05-15 17:07:18 +0100159import android.net.MatchAllNetworkSpecifier;
Ken Chen6df7a902021-04-09 15:08:42 +0800160import android.net.NativeNetworkConfig;
161import android.net.NativeNetworkType;
junyulaid05a1922019-01-15 11:32:44 +0800162import android.net.NattSocketKeepalive;
Robert Greenwalt42a0e1e2014-03-19 17:56:12 -0700163import android.net.Network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700164import android.net.NetworkAgent;
Lorenzo Colittiab2fed72020-01-12 22:28:37 +0900165import android.net.NetworkAgentConfig;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700166import android.net.NetworkCapabilities;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800167import android.net.NetworkInfo;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700168import android.net.NetworkInfo.DetailedState;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +0900169import android.net.NetworkMonitorManager;
Jeff Sharkey0f2738e2018-01-18 22:01:59 +0900170import android.net.NetworkPolicyManager;
Sudheer Shanka9967d462021-03-18 19:09:25 +0000171import android.net.NetworkPolicyManager.NetworkPolicyCallback;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900172import android.net.NetworkProvider;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700173import android.net.NetworkRequest;
Chalard Jean28018572020-12-21 18:36:52 +0900174import android.net.NetworkScore;
Etan Cohen1b6d4182017-04-03 17:42:34 -0700175import android.net.NetworkSpecifier;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900176import android.net.NetworkStack;
Jeff Sharkey21062e72011-05-28 20:56:34 -0700177import android.net.NetworkState;
junyulaide41fc22021-01-22 22:46:01 +0800178import android.net.NetworkStateSnapshot;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +0900179import android.net.NetworkTestResultParcelable;
Robert Greenwalt7fe44cb2010-08-27 09:24:29 -0700180import android.net.NetworkUtils;
Ricky Wai7097cc92018-01-23 04:09:45 +0000181import android.net.NetworkWatchlistManager;
James Mattis47db0582021-01-01 14:13:35 -0800182import android.net.OemNetworkPreferences;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900183import android.net.PrivateDnsConfigParcel;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -0800184import android.net.ProfileNetworkPreference;
Jason Monk4d5e20f2014-04-25 15:00:09 -0400185import android.net.ProxyInfo;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700186import android.net.QosCallbackException;
187import android.net.QosFilter;
188import android.net.QosSocketFilter;
189import android.net.QosSocketInfo;
Robert Greenwalt5a901292011-04-28 14:28:50 -0700190import android.net.RouteInfo;
Tyler Weare4314862019-12-05 14:55:30 -0800191import android.net.RouteInfoParcel;
junyulai011b1f12019-01-03 18:50:15 +0800192import android.net.SocketKeepalive;
markchien5e866652019-09-30 14:40:57 +0800193import android.net.TetheringManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900194import android.net.TransportInfo;
Paul Jensen8b5fc622014-05-07 15:27:40 -0400195import android.net.UidRange;
Chiachang Wang28afaff2020-12-10 22:24:47 +0800196import android.net.UidRangeParcel;
junyulai2050bed2021-01-23 09:46:34 +0800197import android.net.UnderlyingNetworkInfo;
Jason Monka5bf2842013-07-03 17:04:33 -0400198import android.net.Uri;
Benedict Wonga7319912019-11-06 00:20:15 -0800199import android.net.VpnManager;
Lorenzo Colittia5a903d2021-02-04 00:18:27 +0900200import android.net.VpnTransportInfo;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900201import android.net.connectivity.ConnectivityCompatChanges;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900202import android.net.metrics.IpConnectivityLog;
Hugo Benichi134a18c2016-04-21 15:02:38 +0900203import android.net.metrics.NetworkEvent;
paulhu0e79d952021-06-09 16:11:35 +0800204import android.net.netd.aidl.NativeUidRangeConfig;
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +0900205import android.net.networkstack.ModuleNetworkStackClient;
206import android.net.networkstack.NetworkStackClientBase;
Chalard Jeand4900722022-02-06 12:25:38 +0900207import android.net.networkstack.aidl.NetworkMonitorParameters;
paulhu7c0a2e62021-01-08 00:51:49 +0800208import android.net.resolv.aidl.DnsHealthEventParcel;
209import android.net.resolv.aidl.IDnsResolverUnsolicitedEventListener;
210import android.net.resolv.aidl.Nat64PrefixEventParcel;
211import android.net.resolv.aidl.PrivateDnsValidationEventParcel;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900212import android.net.shared.PrivateDnsConfig;
he_won.hwang881307a2022-03-15 21:23:52 +0900213import android.net.wifi.WifiInfo;
lucaslinb961efc2021-01-21 02:03:17 +0800214import android.os.BatteryStatsManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800215import android.os.Binder;
Dianne Hackborn66dd0332015-12-09 17:22:26 -0800216import android.os.Build;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700217import android.os.Bundle;
Paul Hu3c8c8102022-08-25 07:06:16 +0000218import android.os.ConditionVariable;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800219import android.os.Handler;
Wink Saville775aad62010-09-02 19:23:52 -0700220import android.os.HandlerThread;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700221import android.os.IBinder;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800222import android.os.Looper;
223import android.os.Message;
Robert Greenwalt15a41532012-08-21 19:27:00 -0700224import android.os.Messenger;
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -0700225import android.os.ParcelFileDescriptor;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +0900226import android.os.Parcelable;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800227import android.os.PersistableBundle;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700228import android.os.PowerManager;
Jeff Sharkey69fc5f82012-09-06 17:54:29 -0700229import android.os.Process;
lucaslin1193a5d2021-01-21 02:04:15 +0800230import android.os.RemoteCallbackList;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700231import android.os.RemoteException;
Hugo Benichia590ab82017-05-11 13:16:17 +0900232import android.os.ServiceSpecificException;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900233import android.os.SystemClock;
Anil Admale1a28862019-04-05 10:06:37 -0700234import android.os.SystemProperties;
Dianne Hackborn22986892012-08-29 18:32:08 -0700235import android.os.UserHandle;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400236import android.os.UserManager;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800237import android.provider.Settings;
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +0900238import android.sysprop.NetworkProperties;
Tyler Wear72388212021-09-09 14:49:02 -0700239import android.system.ErrnoException;
Wink Saville32506bc2013-06-29 21:10:57 -0700240import android.telephony.TelephonyManager;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700241import android.text.TextUtils;
lucaslin1193a5d2021-01-21 02:04:15 +0800242import android.util.ArrayMap;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900243import android.util.ArraySet;
Serik Beketayev47c4d4d2021-02-06 09:19:47 +0000244import android.util.LocalLog;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600245import android.util.Log;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900246import android.util.Pair;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900247import android.util.Range;
Chad Brubakerb7652cd2013-06-14 11:16:51 -0700248import android.util.SparseArray;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700249import android.util.SparseIntArray;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800250
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800251import androidx.annotation.RequiresApi;
252
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +0900253import com.android.connectivity.resources.R;
Jason Monka5bf2842013-07-03 17:04:33 -0400254import com.android.internal.annotations.GuardedBy;
Paul Jensenbd2f32f2015-06-10 11:22:17 -0400255import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -0700256import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900257import com.android.internal.util.MessageUtils;
Chiachang Wang62740142020-11-02 16:51:24 +0800258import com.android.modules.utils.BasicShellCommandHandler;
Chalard Jean524f0b12021-10-25 21:11:56 +0900259import com.android.modules.utils.build.SdkLevel;
lucaslin66f44212021-02-23 01:12:55 +0800260import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
chiachangwang18a6e8c2022-12-01 00:22:34 +0000261import com.android.net.module.util.BinderUtils;
Chalard Jean1d420b32022-10-12 16:39:37 +0900262import com.android.net.module.util.BitUtils;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +0900263import com.android.net.module.util.CollectionUtils;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900264import com.android.net.module.util.DeviceConfigUtils;
Patrick Rohr9f371f02022-03-04 15:14:27 +0100265import com.android.net.module.util.InterfaceParams;
Chalard Jean79162542020-08-19 16:07:22 +0900266import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
267import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
Remi NGUYEN VAN79b241b2021-03-04 17:46:46 +0900268import com.android.net.module.util.LocationPermissionChecker;
Junyu Lai00d92df2022-07-05 11:01:52 +0800269import com.android.net.module.util.PerUidCounter;
paulhudf23d662021-01-25 18:53:17 +0800270import com.android.net.module.util.PermissionUtils;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100271import com.android.net.module.util.TcUtils;
Xiao Ma09c07272021-07-01 14:00:34 +0000272import com.android.net.module.util.netlink.InetDiagMessage;
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800273import com.android.networkstack.apishim.BroadcastOptionsShimImpl;
274import com.android.networkstack.apishim.ConstantsShim;
275import com.android.networkstack.apishim.common.BroadcastOptionsShim;
276import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900277import com.android.server.connectivity.ApplicationSelfCertifiedNetworkCapabilities;
Chalard Jean7284daa2019-05-30 14:58:29 +0900278import com.android.server.connectivity.AutodestructReference;
chiachangwang3d60bac2023-01-17 14:38:08 +0000279import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker;
Chalard Jean23f1bfd2023-01-24 17:11:27 +0900280import com.android.server.connectivity.AutomaticOnOffKeepaliveTracker.AutomaticOnOffKeepalive;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800281import com.android.server.connectivity.CarrierPrivilegeAuthenticator;
Hungming Cheneb15a2d2022-01-16 15:15:57 +0800282import com.android.server.connectivity.ClatCoordinator;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900283import com.android.server.connectivity.ConnectivityFlags;
Erik Kline32120082017-12-13 19:40:49 +0900284import com.android.server.connectivity.DnsManager;
dalyk1720e542018-03-05 12:42:22 -0500285import com.android.server.connectivity.DnsManager.PrivateDnsValidationUpdate;
Tyler Wear72388212021-09-09 14:49:02 -0700286import com.android.server.connectivity.DscpPolicyTracker;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900287import com.android.server.connectivity.FullScore;
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900288import com.android.server.connectivity.InvalidTagException;
chiachangwang9ef4ffe2023-01-18 01:19:27 +0000289import com.android.server.connectivity.KeepaliveTracker;
Charles He9369e612017-05-15 17:07:18 +0100290import com.android.server.connectivity.LingerMonitor;
Christopher Wileyfcc0d9f2016-10-11 13:26:03 -0700291import com.android.server.connectivity.MockableSystemProperties;
Chalard Jean43aae652022-09-14 21:33:06 +0900292import com.android.server.connectivity.MultinetworkPolicyTracker;
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700293import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600294import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti74c205f2016-08-22 16:30:00 +0900295import com.android.server.connectivity.NetworkNotificationManager;
296import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900297import com.android.server.connectivity.NetworkOffer;
Chalard Jean0606fc82022-12-14 20:34:43 +0900298import com.android.server.connectivity.NetworkPreferenceList;
Chalard Jean96a4f4b2019-12-10 22:16:53 +0900299import com.android.server.connectivity.NetworkRanker;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700300import com.android.server.connectivity.PermissionMonitor;
Chalard Jean0606fc82022-12-14 20:34:43 +0900301import com.android.server.connectivity.ProfileNetworkPreferenceInfo;
Chalard Jean5d70ba42018-06-07 16:44:04 +0900302import com.android.server.connectivity.ProxyTracker;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700303import com.android.server.connectivity.QosCallbackTracker;
Sooraj Sasindran499117f2021-11-29 12:40:09 -0800304import com.android.server.connectivity.UidRangeUtils;
lucaslin3ba7cc22022-12-19 02:35:33 +0000305import com.android.server.connectivity.VpnNetworkPreferenceInfo;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800306import com.android.server.connectivity.wear.CompanionDeviceManagerProxyService;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600307
Josh Gao461a1222020-06-16 15:58:11 -0700308import libcore.io.IoUtils;
309
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900310import org.xmlpull.v1.XmlPullParserException;
311
The Android Open Source Project28527d22009-03-03 19:31:44 -0800312import java.io.FileDescriptor;
Patrick Rohr2857ac42022-01-21 14:58:16 +0100313import java.io.IOException;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900314import java.io.InterruptedIOException;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800315import java.io.PrintWriter;
Chalard Jean524f0b12021-10-25 21:11:56 +0900316import java.io.Writer;
Wink Savilledc5d1ba2011-07-14 12:23:28 -0700317import java.net.Inet4Address;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700318import java.net.InetAddress;
Lorenzo Colitti3be9df12021-02-04 01:47:38 +0900319import java.net.InetSocketAddress;
Motomu Utsumi93a22182023-03-16 17:04:21 +0900320import java.net.SocketException;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700321import java.net.UnknownHostException;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700322import java.util.ArrayList;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700323import java.util.Arrays;
Robert Greenwalta7dfbd32010-06-15 15:43:39 -0700324import java.util.Collection;
James Mattis60b84b22020-11-03 15:54:33 -0800325import java.util.Collections;
Hugo Benichia480ba52018-09-03 08:19:02 +0900326import java.util.Comparator;
junyulaif2c67e42018-08-07 19:50:45 +0800327import java.util.ConcurrentModificationException;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700328import java.util.HashMap;
Jeff Sharkeya47d7a12011-06-16 15:07:48 -0700329import java.util.HashSet;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700330import java.util.List;
Vinit Deshapnde30ad2542013-08-21 13:09:01 -0700331import java.util.Map;
Chalard Jean524f0b12021-10-25 21:11:56 +0900332import java.util.NoSuchElementException;
Robert Greenwalte525a0a2014-09-30 16:50:07 -0700333import java.util.Objects;
Chalard Jeanb2a49912018-01-16 18:43:05 +0900334import java.util.Set;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600335import java.util.SortedSet;
Chalard Jean49707572019-12-10 21:07:02 +0900336import java.util.StringJoiner;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -0600337import java.util.TreeSet;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900338import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800339
340/**
341 * @hide
342 */
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800343public class ConnectivityService extends IConnectivityManager.Stub
344 implements PendingIntent.OnFinished {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900345 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project28527d22009-03-03 19:31:44 -0800346
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900347 private static final String DIAG_ARG = "--diag";
Erik Klined364a242017-05-12 16:52:48 +0900348 public static final String SHORT_ARG = "--short";
Hugo Benichi5df91ce2018-09-03 08:32:56 +0900349 private static final String NETWORK_ARG = "networks";
350 private static final String REQUEST_ARG = "requests";
Ken Chene6d511f2022-01-25 11:10:42 +0800351 private static final String TRAFFICCONTROLLER_ARG = "trafficcontroller";
Erik Klined364a242017-05-12 16:52:48 +0900352
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900353 private static final boolean DBG = true;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +0900354 private static final boolean DDBG = Log.isLoggable(TAG, Log.DEBUG);
355 private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE);
The Android Open Source Project28527d22009-03-03 19:31:44 -0800356
Lorenzo Colittiac136a02016-01-22 04:04:57 +0900357 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkey921ebf22011-05-19 17:12:49 -0700358
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100359 /**
360 * Default URL to use for {@link #getCaptivePortalServerUrl()}. This should not be changed
361 * by OEMs for configuration purposes, as this value is overridden by
paulhu56e09df2021-03-17 20:30:33 +0800362 * ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL.
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +0100363 * R.string.config_networkCaptivePortalServerUrl should be overridden instead for this purpose
364 * (preferably via runtime resource overlays).
365 */
366 private static final String DEFAULT_CAPTIVE_PORTAL_HTTP_URL =
367 "http://connectivitycheck.gstatic.com/generate_204";
368
Jeff Sharkey366e0b72012-08-04 15:24:58 -0700369 // TODO: create better separation between radio types and network types
370
Robert Greenwalt2034b912009-08-12 16:08:25 -0700371 // how long to wait before switching back to a radio's default network
372 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
373 // system property that can override the above value
374 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
375 "android.telephony.apn-restore";
376
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900377 // How long to wait before putting up a "This network doesn't have an Internet connection,
378 // connect anyway?" dialog after the user selects a network that doesn't validate.
379 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
380
Chalard Jean5fb43c72022-09-08 19:03:14 +0900381 // How long to wait before considering that a network is bad in the absence of any form
382 // of connectivity (valid, partial, captive portal). If none has been detected after this
383 // delay, the stack considers this network bad, which may affect how it's handled in ranking
384 // according to config_networkAvoidBadWifi.
Chalard Jeane63c42f2022-09-16 19:31:45 +0900385 // Timeout in case the "actively prefer bad wifi" feature is on
386 private static final int ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 20 * 1000;
387 // Timeout in case the "actively prefer bad wifi" feature is off
388 private static final int DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS = 8 * 1000;
Chalard Jean5fb43c72022-09-08 19:03:14 +0900389
junyulai0ac374f2020-12-14 18:41:52 +0800390 // Default to 30s linger time-out, and 5s for nascent network. Modifiable only for testing.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900391 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
392 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
junyulai0ac374f2020-12-14 18:41:52 +0800393 private static final int DEFAULT_NASCENT_DELAY_MS = 5_000;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700394
Sudheer Shanka2453a3a2022-11-29 15:15:50 -0800395 // Delimiter used when creating the broadcast delivery group for sending
396 // CONNECTIVITY_ACTION broadcast.
397 private static final char DELIVERY_GROUP_KEY_DELIMITER = ';';
398
he_won.hwang881307a2022-03-15 21:23:52 +0900399 // The maximum value for the blocking validation result, in milliseconds.
Lorenzo Colitti580d0d52022-10-13 19:56:58 +0900400 public static final int MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS = 10000;
he_won.hwang881307a2022-03-15 21:23:52 +0900401
Daniel Brightf9e945b2020-06-15 16:10:01 -0700402 // The maximum number of network request allowed per uid before an exception is thrown.
Chalard Jean9473c982021-07-29 20:03:04 +0900403 @VisibleForTesting
404 static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700405
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900406 // The maximum number of network request allowed for system UIDs before an exception is thrown.
James Mattis20a4a8b2021-03-28 17:41:09 -0700407 @VisibleForTesting
408 static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
Lorenzo Colitti6dba5882021-03-30 19:29:00 +0900409
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900410 @VisibleForTesting
411 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
junyulai0ac374f2020-12-14 18:41:52 +0800412 @VisibleForTesting
413 protected int mNascentDelayMs;
Chalard Jean0702f982021-09-16 21:50:07 +0900414 // True if the cell radio of the device is capable of time-sharing.
415 @VisibleForTesting
416 protected boolean mCellularRadioTimesharingCapable = true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +0900417
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800418 // How long to delay to removal of a pending intent based request.
paulhu56e09df2021-03-17 20:30:33 +0800419 // See ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
Jeremy Joslin1d3acf92014-12-03 17:15:28 -0800420 private final int mReleasePendingIntentDelayMs;
421
Chalard Jean46bfbf02022-02-02 00:56:25 +0900422 private final MockableSystemProperties mSystemProperties;
Lorenzo Colitticd447b22017-03-21 18:54:11 +0900423
Motomu Utsumif360aa62023-01-30 17:52:20 +0900424 private final PermissionMonitor mPermissionMonitor;
Sreeram Ramachandranae6c5072014-09-24 09:16:19 -0700425
Chalard Jean9473c982021-07-29 20:03:04 +0900426 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800427 final RequestInfoPerUidCounter mNetworkRequestCounter;
James Mattis20a4a8b2021-03-28 17:41:09 -0700428 @VisibleForTesting
Junyu Lai00d92df2022-07-05 11:01:52 +0800429 final RequestInfoPerUidCounter mSystemNetworkRequestCounter;
Daniel Brightf9e945b2020-06-15 16:10:01 -0700430
Lorenzo Colittibcd692f2021-01-15 01:29:01 +0900431 private volatile boolean mLockdownEnabled;
Jeff Sharkeyebcc7972012-08-25 00:05:46 -0700432
junyulaif2c67e42018-08-07 19:50:45 +0800433 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000434 * Stale copy of uid blocked reasons provided by NPMS. As long as they are accessed only in
435 * internal handler thread, they don't need a lock.
junyulaif2c67e42018-08-07 19:50:45 +0800436 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900437 private final SparseIntArray mUidBlockedReasons = new SparseIntArray();
junyulaif2c67e42018-08-07 19:50:45 +0800438
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900439 private final Context mContext;
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +0900440 private final ConnectivityResources mResources;
Paul Hu96f1cbb2021-01-26 02:53:06 +0000441 // The Context is created for UserHandle.ALL.
442 private final Context mUserAllContext;
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +0900443 private final Dependencies mDeps;
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +0900444 private final ConnectivityFlags mFlags;
Robert Greenwalt986c7412010-09-08 15:24:47 -0700445 // 0 is full bad, 100 is full good
Robert Greenwalt986c7412010-09-08 15:24:47 -0700446 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project28527d22009-03-03 19:31:44 -0800447
Chenbo Feng15416292018-11-08 17:36:21 -0800448 @VisibleForTesting
Luke Huang81413192019-03-16 00:31:46 +0800449 protected IDnsResolver mDnsResolver;
450 @VisibleForTesting
Chenbo Feng15416292018-11-08 17:36:21 -0800451 protected INetd mNetd;
Tyler Wear72388212021-09-09 14:49:02 -0700452 private DscpPolicyTracker mDscpPolicyTracker = null;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900453 private final NetworkStatsManager mStatsManager;
454 private final NetworkPolicyManager mPolicyManager;
Wayne Ma2fde98c2022-01-17 18:04:05 +0800455 private final BpfNetMaps mBpfNetMaps;
Robert Greenwalt355205c2011-05-10 15:05:02 -0700456
Benedict Wong493e04b2018-11-09 14:45:34 -0800457 /**
458 * TestNetworkService (lazily) created upon first usage. Locked to prevent creation of multiple
459 * instances.
460 */
461 @GuardedBy("mTNSLock")
462 private TestNetworkService mTNS;
Igor Chernyshev9dac6602022-12-13 19:28:32 -0800463 private final CompanionDeviceManagerProxyService mCdmps;
Benedict Wong493e04b2018-11-09 14:45:34 -0800464
465 private final Object mTNSLock = new Object();
466
Robert Greenwaltdebf0e02014-08-06 12:00:25 -0700467 private String mCurrentTcpBufferSizes;
468
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900469 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
chiachangwangf1b1fb42023-04-14 07:32:43 +0000470 new Class[] {
471 ConnectivityService.class,
472 NetworkAgent.class,
473 NetworkAgentInfo.class,
474 AutomaticOnOffKeepaliveTracker.class });
Lorenzo Colittib54bea92016-04-05 17:52:16 +0900475
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500476 private enum ReapUnvalidatedNetworks {
Paul Jensend2a43f92015-06-25 13:25:07 -0400477 // Tear down networks that have no chance (e.g. even if validated) of becoming
478 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500479 // all networks have been rematched against all NetworkRequests.
480 REAP,
Paul Jensend2a43f92015-06-25 13:25:07 -0400481 // Don't reap networks. This should be passed when some networks have not yet been
482 // rematched against all NetworkRequests.
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500483 DONT_REAP
Chalard Jeand6c33dc2018-06-04 13:33:12 +0900484 }
Paul Jensen5c4e5fc2014-11-25 12:33:08 -0500485
Lorenzo Colitti2666be82016-09-09 18:48:56 +0900486 private enum UnneededFor {
487 LINGER, // Determine whether this network is unneeded and should be lingered.
488 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
489 }
490
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -0700491 /**
paulhuaa0743d2021-05-26 21:56:03 +0800492 * For per-app preferences, requests contain an int to signify which request
paulhu48291862021-07-14 14:53:57 +0800493 * should have priority. The order is passed to netd which will use it together
494 * with UID ranges to generate the corresponding IP rule. This serves to
495 * direct device-originated data traffic of the specific UIDs to the correct
paulhuaa0743d2021-05-26 21:56:03 +0800496 * default network for each app.
paulhu48291862021-07-14 14:53:57 +0800497 * Order ints passed to netd must be in the 0~999 range. Larger values code for
chiachangwang9473c592022-07-15 02:25:52 +0000498 * a lower priority, see {@link NativeUidRangeConfig}.
paulhue9913722021-05-26 15:19:20 +0800499 *
paulhu48291862021-07-14 14:53:57 +0800500 * Requests that don't code for a per-app preference use PREFERENCE_ORDER_INVALID.
501 * The default request uses PREFERENCE_ORDER_DEFAULT.
paulhue9913722021-05-26 15:19:20 +0800502 */
paulhu48291862021-07-14 14:53:57 +0800503 // Used when sending to netd to code for "no order".
504 static final int PREFERENCE_ORDER_NONE = 0;
505 // Order for requests that don't code for a per-app preference. As it is
506 // out of the valid range, the corresponding order should be
507 // PREFERENCE_ORDER_NONE when sending to netd.
paulhue9913722021-05-26 15:19:20 +0800508 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800509 static final int PREFERENCE_ORDER_INVALID = Integer.MAX_VALUE;
paulhuaa0743d2021-05-26 21:56:03 +0800510 // As a security feature, VPNs have the top priority.
paulhu48291862021-07-14 14:53:57 +0800511 static final int PREFERENCE_ORDER_VPN = 0; // Netd supports only 0 for VPN.
512 // Order of per-app OEM preference. See {@link #setOemNetworkPreference}.
paulhue9913722021-05-26 15:19:20 +0800513 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800514 static final int PREFERENCE_ORDER_OEM = 10;
515 // Order of per-profile preference, such as used by enterprise networks.
paulhue9913722021-05-26 15:19:20 +0800516 // See {@link #setProfileNetworkPreference}.
517 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800518 static final int PREFERENCE_ORDER_PROFILE = 20;
519 // Order of user setting to prefer mobile data even when networks with
paulhuaa0743d2021-05-26 21:56:03 +0800520 // better scores are connected.
521 // See {@link ConnectivitySettingsManager#setMobileDataPreferredUids}
paulhue9913722021-05-26 15:19:20 +0800522 @VisibleForTesting
paulhu48291862021-07-14 14:53:57 +0800523 static final int PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED = 30;
Chalard Jeane6c95272022-01-25 21:04:21 +0900524 // Preference order that signifies the network shouldn't be set as a default network for
525 // the UIDs, only give them access to it. TODO : replace this with a boolean
526 // in NativeUidRangeConfig
527 @VisibleForTesting
528 static final int PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT = 999;
529 // Bound for the lowest valid preference order.
530 static final int PREFERENCE_ORDER_LOWEST = 999;
paulhue9913722021-05-26 15:19:20 +0800531
532 /**
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700533 * used internally to clear a wakelock when transitioning
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700534 * from one net to another. Clear happens when we get a new
535 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
536 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700537 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700538 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltccb36f92010-09-24 14:32:21 -0700539
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700540 /**
541 * used internally to reload global proxy settings
542 */
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700543 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700544
Robert Greenwalt34848c02011-03-25 13:09:25 -0700545 /**
Jason Monka69f1b02013-10-10 14:02:51 -0400546 * PAC manager has received new port.
547 */
548 private static final int EVENT_PROXY_HAS_CHANGED = 16;
549
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700550 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900551 * used internally when registering NetworkProviders
552 * obj = NetworkProviderInfo
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700553 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900554 private static final int EVENT_REGISTER_NETWORK_PROVIDER = 17;
Robert Greenwalt7e45d112014-04-11 15:53:27 -0700555
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700556 /**
557 * used internally when registering NetworkAgents
558 * obj = Messenger
559 */
560 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
561
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700562 /**
563 * used to add a network request
564 * includes a NetworkRequestInfo
565 */
566 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
567
568 /**
569 * indicates a timeout period is over - check if we had a network yet or not
Erik Kline0c04b742016-07-07 16:50:58 +0900570 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700571 * cancel it.
572 * includes a NetworkRequestInfo
573 */
574 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
575
576 /**
577 * used to add a network listener - no request
578 * includes a NetworkRequestInfo
579 */
580 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
581
582 /**
583 * used to remove a network request, either a listener or a real request
Paul Jensen961cb0d2014-05-16 14:31:12 -0400584 * arg1 = UID of caller
585 * obj = NetworkRequest
Robert Greenwaltf99b8392014-03-26 16:47:06 -0700586 */
587 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
588
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700589 /**
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900590 * used internally when registering NetworkProviders
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700591 * obj = Messenger
592 */
Lorenzo Colittia86fae72020-01-10 00:40:28 +0900593 private static final int EVENT_UNREGISTER_NETWORK_PROVIDER = 23;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -0700594
Robert Greenwalt520d6dc2014-06-25 16:45:57 -0700595 /**
596 * used internally to expire a wakelock when transitioning
597 * from one net to another. Expire happens when we fail to find
598 * a new network (typically after 1 minute) -
599 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
600 * a replacement network.
601 */
602 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
603
Robert Greenwaltdc2d5612014-08-13 13:43:32 -0700604 /**
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800605 * used to add a network request with a pending intent
Paul Jensenc8873fc2015-06-17 14:15:39 -0400606 * obj = NetworkRequestInfo
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800607 */
608 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
609
610 /**
611 * used to remove a pending intent and its associated network request.
612 * arg1 = UID of caller
613 * obj = PendingIntent
614 */
615 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
616
Lorenzo Colitti6947c062015-04-03 16:38:52 +0900617 /**
618 * used to specify whether a network should be used even if unvalidated.
619 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
620 * arg2 = whether to remember this choice in the future (1 or 0)
621 * obj = network
622 */
623 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
624
625 /**
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700626 * used internally to (re)configure always-on networks.
Erik Kline05f2b402015-04-30 12:58:40 +0900627 */
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -0700628 private static final int EVENT_CONFIGURE_ALWAYS_ON_NETWORKS = 30;
Erik Kline05f2b402015-04-30 12:58:40 +0900629
Paul Jensenc8873fc2015-06-17 14:15:39 -0400630 /**
631 * used to add a network listener with a pending intent
632 * obj = NetworkRequestInfo
633 */
634 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
635
Hugo Benichid6b510a2017-04-06 17:22:18 +0900636 /**
637 * used to specify whether a network should not be penalized when it becomes unvalidated.
638 */
639 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
640
641 /**
Cody Kestingf1120be2020-08-03 18:01:40 -0700642 * used to handle reported network connectivity. May trigger revalidation of a network.
Hugo Benichid6b510a2017-04-06 17:22:18 +0900643 */
Cody Kestingf1120be2020-08-03 18:01:40 -0700644 private static final int EVENT_REPORT_NETWORK_CONNECTIVITY = 36;
Hugo Benichid6b510a2017-04-06 17:22:18 +0900645
Erik Kline31b4a9e2018-01-11 21:07:29 +0900646 // Handle changes in Private DNS settings.
647 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
648
dalyk1720e542018-03-05 12:42:22 -0500649 // Handle private DNS validation status updates.
650 private static final int EVENT_PRIVATE_DNS_VALIDATION_UPDATE = 38;
651
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900652 /**
653 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the network has
654 * been tested.
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800655 * obj = {@link NetworkTestedResults} representing information sent from NetworkMonitor.
656 * data = PersistableBundle of extras passed from NetworkMonitor. If {@link
657 * NetworkMonitorCallbacks#notifyNetworkTested} is called, this will be null.
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900658 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900659 private static final int EVENT_NETWORK_TESTED = 41;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900660
661 /**
662 * Event for NetworkMonitor/NetworkAgentInfo to inform ConnectivityService that the private DNS
663 * config was resolved.
664 * obj = PrivateDnsConfig
665 * arg2 = netid
666 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900667 private static final int EVENT_PRIVATE_DNS_CONFIG_RESOLVED = 42;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900668
669 /**
670 * Request ConnectivityService display provisioning notification.
671 * arg1 = Whether to make the notification visible.
672 * arg2 = NetID.
673 * obj = Intent to be launched when notification selected by user, null if !arg1.
674 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900675 private static final int EVENT_PROVISIONING_NOTIFICATION = 43;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900676
677 /**
lucaslin2240ef62019-03-12 13:08:03 +0800678 * Used to specify whether a network should be used even if connectivity is partial.
679 * arg1 = whether to accept the network if its connectivity is partial (1 for true or 0 for
680 * false)
681 * arg2 = whether to remember this choice in the future (1 for true or 0 for false)
682 * obj = network
683 */
lucaslin444d43a2020-02-20 16:56:59 +0800684 private static final int EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY = 44;
lucaslin2240ef62019-03-12 13:08:03 +0800685
686 /**
lucasline117e2e2019-10-22 18:27:33 +0800687 * Event for NetworkMonitor to inform ConnectivityService that the probe status has changed.
688 * Both of the arguments are bitmasks, and the value of bits come from
689 * INetworkMonitor.NETWORK_VALIDATION_PROBE_*.
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +0900690 * arg1 = unused
691 * arg2 = netId
692 * obj = A Pair of integers: the bitmasks of, respectively, completed and successful probes.
lucasline117e2e2019-10-22 18:27:33 +0800693 */
lucaslin444d43a2020-02-20 16:56:59 +0800694 public static final int EVENT_PROBE_STATUS_CHANGED = 45;
lucasline117e2e2019-10-22 18:27:33 +0800695
696 /**
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900697 * Event for NetworkMonitor to inform ConnectivityService that captive portal data has changed.
698 * arg1 = unused
699 * arg2 = netId
700 * obj = captive portal data
701 */
lucaslin444d43a2020-02-20 16:56:59 +0800702 private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +0900703
704 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +0900705 * Used by setRequireVpnForUids.
706 * arg1 = whether the specified UID ranges are required to use a VPN.
707 * obj = Array of UidRange objects.
708 */
709 private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
710
711 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900712 * Used internally when setting the default networks for OemNetworkPreferences.
713 * obj = Pair<OemNetworkPreferences, listener>
James Mattis45d81842021-01-10 14:24:24 -0800714 */
715 private static final int EVENT_SET_OEM_NETWORK_PREFERENCE = 48;
716
717 /**
lucaslin1193a5d2021-01-21 02:04:15 +0800718 * Used to indicate the system default network becomes active.
719 */
720 private static final int EVENT_REPORT_NETWORK_ACTIVITY = 49;
721
722 /**
Chalard Jeanb5a139f2021-02-25 21:46:34 +0900723 * Used internally when setting a network preference for a user profile.
724 * obj = Pair<ProfileNetworkPreference, Listener>
725 */
726 private static final int EVENT_SET_PROFILE_NETWORK_PREFERENCE = 50;
727
728 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +0000729 * Event to specify that reasons for why an uid is blocked changed.
730 * arg1 = uid
731 * arg2 = blockedReasons
732 */
733 private static final int EVENT_UID_BLOCKED_REASON_CHANGED = 51;
734
735 /**
Chalard Jeancdd68bc2021-01-05 08:40:09 +0900736 * Event to register a new network offer
737 * obj = NetworkOffer
738 */
739 private static final int EVENT_REGISTER_NETWORK_OFFER = 52;
740
741 /**
742 * Event to unregister an existing network offer
743 * obj = INetworkOfferCallback
744 */
745 private static final int EVENT_UNREGISTER_NETWORK_OFFER = 53;
746
747 /**
paulhu51f77dc2021-06-07 02:34:20 +0000748 * Used internally when MOBILE_DATA_PREFERRED_UIDS setting changed.
749 */
750 private static final int EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED = 54;
751
752 /**
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800753 * Event to set temporary allow bad wifi within a limited time to override
754 * {@code config_networkAvoidBadWifi}.
755 */
756 private static final int EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL = 55;
757
758 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100759 * Used internally when INGRESS_RATE_LIMIT_BYTES_PER_SECOND setting changes.
760 */
761 private static final int EVENT_INGRESS_RATE_LIMIT_CHANGED = 56;
762
763 /**
Chalard Jean5fb43c72022-09-08 19:03:14 +0900764 * The initial evaluation period is over for this network.
765 *
766 * If no form of connectivity has been found on this network (valid, partial, captive portal)
767 * then the stack will now consider it to have been determined bad.
768 */
769 private static final int EVENT_INITIAL_EVALUATION_TIMEOUT = 57;
770
771 /**
Hansen Kurli55396972022-10-28 03:31:17 +0000772 * Used internally when the user does not want the network from captive portal app.
773 * obj = Network
774 */
775 private static final int EVENT_USER_DOES_NOT_WANT = 58;
776
777 /**
lucaslin3ba7cc22022-12-19 02:35:33 +0000778 * Event to set VPN as preferred network for specific apps.
779 * obj = VpnNetworkPreferenceInfo
780 */
781 private static final int EVENT_SET_VPN_NETWORK_PREFERENCE = 59;
782
783 /**
chiachangwange0192a72023-02-06 13:25:01 +0000784 * Event to use low TCP polling timer used in automatic on/off keepalive temporarily.
785 */
786 private static final int EVENT_SET_LOW_TCP_POLLING_UNTIL = 60;
787
788 /**
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900789 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
790 * should be shown.
791 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900792 private static final int PROVISIONING_NOTIFICATION_SHOW = 1;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900793
794 /**
795 * Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
796 * should be hidden.
797 */
Chalard Jeanfbab6d42019-09-26 18:03:47 +0900798 private static final int PROVISIONING_NOTIFICATION_HIDE = 0;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +0900799
Chiachang Wang6eac9fb2021-06-17 22:11:30 +0800800 /**
801 * The maximum alive time to allow bad wifi configuration for testing.
802 */
803 private static final long MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS = 5 * 60 * 1000L;
804
Patrick Rohr2857ac42022-01-21 14:58:16 +0100805 /**
chiachangwange0192a72023-02-06 13:25:01 +0000806 * The maximum alive time to decrease TCP polling timer in automatic on/off keepalive for
807 * testing.
808 */
809 private static final long MAX_TEST_LOW_TCP_POLLING_UNTIL_MS = 5 * 60 * 1000L;
810
811 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +0100812 * The priority of the tc police rate limiter -- smaller value is higher priority.
813 * This value needs to be coordinated with PRIO_CLAT, PRIO_TETHER4, and PRIO_TETHER6.
814 */
815 private static final short TC_PRIO_POLICE = 1;
816
817 /**
818 * The BPF program attached to the tc-police hook to account for to-be-dropped traffic.
819 */
820 private static final String TC_POLICE_BPF_PROG_PATH =
Maciej Żenczykowski6d116d02022-05-16 13:59:12 -0700821 "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
Patrick Rohr2857ac42022-01-21 14:58:16 +0100822
Hugo Benichi47011212017-03-30 10:46:05 +0900823 private static String eventName(int what) {
824 return sMagicDecoderRing.get(what, Integer.toString(what));
825 }
826
paulhua10d8212020-11-10 15:32:56 +0800827 private static IDnsResolver getDnsResolver(Context context) {
Lorenzo Colitti34a294f2021-04-15 18:03:54 +0900828 final DnsResolverServiceManager dsm = context.getSystemService(
829 DnsResolverServiceManager.class);
830 return IDnsResolver.Stub.asInterface(dsm.getService());
Luke Huang81413192019-03-16 00:31:46 +0800831 }
832
Cody Kesting73708bf2019-12-18 10:57:50 -0800833 /** Handler thread used for all of the handlers below. */
Lorenzo Colitti0891bc42015-08-07 20:17:27 +0900834 @VisibleForTesting
835 protected final HandlerThread mHandlerThread;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700836 /** Handler used for internal events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700837 final private InternalHandler mHandler;
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -0700838 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalte20f7a22014-04-18 15:25:25 -0700839 final private NetworkStateTrackerHandler mTrackerHandler;
Cody Kesting73708bf2019-12-18 10:57:50 -0800840 /** Handler used for processing {@link android.net.ConnectivityDiagnosticsManager} events */
841 @VisibleForTesting
842 final ConnectivityDiagnosticsHandler mConnectivityDiagnosticsHandler;
843
Erik Kline32120082017-12-13 19:40:49 +0900844 private final DnsManager mDnsManager;
Chalard Jean020b93a2022-09-01 13:20:14 +0900845 @VisibleForTesting
846 final NetworkRanker mNetworkRanker;
Robert Greenwalt2034b912009-08-12 16:08:25 -0700847
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400848 private boolean mSystemReady;
Dianne Hackborna417ff82009-12-08 19:45:14 -0800849 private Intent mInitialBroadcast;
Mike Lockwoodfde2b762009-08-14 14:18:49 -0400850
Chalard Jean46bfbf02022-02-02 00:56:25 +0900851 private final PowerManager.WakeLock mNetTransitionWakeLock;
Jeremy Joslin60d379b2014-11-05 10:32:09 -0800852 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt93dc1042010-06-15 12:19:37 -0700853
Chalard Jean5d70ba42018-06-07 16:44:04 +0900854 // A helper object to track the current default HTTP proxy. ConnectivityService needs to tell
855 // the world when it changes.
Irina Dumitrescude132bb2018-12-05 16:19:47 +0000856 @VisibleForTesting
857 protected final ProxyTracker mProxyTracker;
Jason Monka5bf2842013-07-03 17:04:33 -0400858
Erik Kline05f2b402015-04-30 12:58:40 +0900859 final private SettingsObserver mSettingsObserver;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -0700860
Chalard Jean46bfbf02022-02-02 00:56:25 +0900861 private final UserManager mUserManager;
Julia Reynoldsc8e3a712014-06-24 10:56:55 -0400862
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700863 // the set of network types that can only be enabled by system/sig apps
Chalard Jean46bfbf02022-02-02 00:56:25 +0900864 private final List<Integer> mProtectedNetworks;
Robert Greenwalt6cac0742011-06-21 17:26:14 -0700865
Valentin Iftime9fa35092019-09-24 13:32:13 +0200866 private Set<String> mWolSupportedInterfaces;
867
Roshan Pius08c94fb2020-01-16 12:17:17 -0800868 private final TelephonyManager mTelephonyManager;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -0800869 private final CarrierPrivilegeAuthenticator mCarrierPrivilegeAuthenticator;
Cody Kesting83bb5fa2020-01-05 14:06:39 -0800870 private final AppOpsManager mAppOpsManager;
871
872 private final LocationPermissionChecker mLocationPermissionChecker;
John Spurlock1f5cec72013-06-24 14:20:23 -0400873
chiachangwang3d60bac2023-01-17 14:38:08 +0000874 private final AutomaticOnOffKeepaliveTracker mKeepaliveTracker;
Chalard Jean46bfbf02022-02-02 00:56:25 +0900875 private final QosCallbackTracker mQosCallbackTracker;
876 private final NetworkNotificationManager mNotifier;
877 private final LingerMonitor mLingerMonitor;
Lorenzo Colitti0b798a82015-06-15 14:29:22 +0900878
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700879 // sequence number of NetworkRequests
junyulai70afb0c2020-12-14 18:51:02 +0800880 private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
Robert Greenwalt0eb55c12014-05-18 16:22:10 -0700881
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +0900882 // Sequence number for NetworkProvider IDs.
883 private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
884 NetworkProvider.FIRST_PROVIDER_ID);
885
Erik Klineedf878b2015-07-09 18:24:03 +0900886 // NetworkRequest activity String log entries.
887 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
888 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
889
Hugo Benichid159fdd2016-07-11 11:05:12 +0900890 // NetworkInfo blocked and unblocked String log entries
Hugo Benichi47011212017-03-30 10:46:05 +0900891 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichid159fdd2016-07-11 11:05:12 +0900892 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
893
Hugo Benichi47011212017-03-30 10:46:05 +0900894 private static final int MAX_WAKELOCK_LOGS = 20;
895 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi88f49ac2017-09-05 13:25:07 +0900896 private int mTotalWakelockAcquisitions = 0;
897 private int mTotalWakelockReleases = 0;
898 private long mTotalWakelockDurationMs = 0;
899 private long mMaxWakelockDurationMs = 0;
900 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichi47011212017-03-30 10:46:05 +0900901
Hugo Benichi208c0102016-07-28 17:53:06 +0900902 private final IpConnectivityLog mMetricsLog;
Hugo Benichibe0c7652016-05-31 16:28:06 +0900903
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700904 @GuardedBy("mBandwidthRequests")
Chalard Jean46bfbf02022-02-02 00:56:25 +0900905 private final SparseArray<Integer> mBandwidthRequests = new SparseArray<>(10);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -0700906
Erik Kline95ecfee2016-10-02 18:02:14 +0900907 @VisibleForTesting
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +0900908 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline95ecfee2016-10-02 18:02:14 +0900909
Lorenzo Colitti389a8142018-01-24 17:35:07 +0900910 @VisibleForTesting
Cody Kesting31f1ff62020-03-05 10:46:02 -0800911 final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
912 new HashMap<>();
Cody Kesting73708bf2019-12-18 10:57:50 -0800913
Patrick Rohr2857ac42022-01-21 14:58:16 +0100914 // Rate limit applicable to all internet capable networks (-1 = disabled). This value is
915 // configured via {@link
916 // ConnectivitySettingsManager#INGRESS_RATE_LIMIT_BYTES_PER_SECOND}
917 // Only the handler thread is allowed to access this field.
918 private long mIngressRateLimit = -1;
919
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900920 // This is the cache for the packageName -> ApplicationSelfCertifiedNetworkCapabilities. This
921 // value can be accessed from both handler thread and any random binder thread. Therefore,
Yuyang Huang2d13d432023-03-13 12:27:40 +0900922 // accessing this value requires holding a lock. The cache is the same across all the users.
Yuyang Huang96e8bfe2023-01-27 17:05:07 +0900923 @GuardedBy("mSelfCertifiedCapabilityCache")
924 private final Map<String, ApplicationSelfCertifiedNetworkCapabilities>
925 mSelfCertifiedCapabilityCache = new HashMap<>();
926
Robert Greenwalt802c1102014-06-02 15:32:02 -0700927 /**
928 * Implements support for the legacy "one network per network type" model.
929 *
930 * We used to have a static array of NetworkStateTrackers, one for each
931 * network type, but that doesn't work any more now that we can have,
932 * for example, more that one wifi network. This class stores all the
933 * NetworkAgentInfo objects that support a given type, but the legacy
934 * API will only see the first one.
935 *
936 * It serves two main purposes:
937 *
938 * 1. Provide information about "the network for a given type" (since this
939 * API only supports one).
940 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
941 * the first network for a given type changes, or if the default network
942 * changes.
943 */
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900944 @VisibleForTesting
945 static class LegacyTypeTracker {
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900946
Lorenzo Colittiebf757d2016-04-08 23:09:09 +0900947 private static final boolean DBG = true;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900948 private static final boolean VDBG = false;
Lorenzo Colitticfb36572014-07-31 23:20:17 +0900949
Robert Greenwalt802c1102014-06-02 15:32:02 -0700950 /**
951 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
952 * Each list holds references to all NetworkAgentInfos that are used to
953 * satisfy requests for that network type.
954 *
955 * This array is built out at startup such that an unsupported network
956 * doesn't get an ArrayList instance, making this a tristate:
957 * unsupported, supported but not active and active.
958 *
959 * The actual lists are populated when we scan the network types that
960 * are supported on this device.
Hugo Benichi389633f2016-06-21 09:48:07 +0900961 *
962 * Threading model:
963 * - addSupportedType() is only called in the constructor
964 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
965 * They are therefore not thread-safe with respect to each other.
966 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
967 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900968 * - getRestoreTimerForType(type) is also synchronized on mTypeLists.
Hugo Benichi389633f2016-06-21 09:48:07 +0900969 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt802c1102014-06-02 15:32:02 -0700970 */
Chalard Jean46bfbf02022-02-02 00:56:25 +0900971 private final ArrayList<NetworkAgentInfo>[] mTypeLists;
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900972 @NonNull
973 private final ConnectivityService mService;
Robert Greenwalt802c1102014-06-02 15:32:02 -0700974
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900975 // Restore timers for requestNetworkForFeature (network type -> timer in ms). Types without
976 // an entry have no timer (equivalent to -1). Lazily loaded.
977 @NonNull
978 private ArrayMap<Integer, Integer> mRestoreTimers = new ArrayMap<>();
979
Chalard Jean3a3f5f22019-04-10 23:07:55 +0900980 LegacyTypeTracker(@NonNull ConnectivityService service) {
981 mService = service;
982 mTypeLists = new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
Robert Greenwalt802c1102014-06-02 15:32:02 -0700983 }
984
Chiachang Wang3bc52762021-11-25 14:17:57 +0800985 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is
986 // addressed.
987 @TargetApi(Build.VERSION_CODES.S)
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +0900988 public void loadSupportedTypes(@NonNull Context ctx, @NonNull TelephonyManager tm) {
989 final PackageManager pm = ctx.getPackageManager();
990 if (pm.hasSystemFeature(FEATURE_WIFI)) {
991 addSupportedType(TYPE_WIFI);
992 }
993 if (pm.hasSystemFeature(FEATURE_WIFI_DIRECT)) {
994 addSupportedType(TYPE_WIFI_P2P);
995 }
996 if (tm.isDataCapable()) {
997 // Telephony does not have granular support for these types: they are either all
998 // supported, or none is supported
999 addSupportedType(TYPE_MOBILE);
1000 addSupportedType(TYPE_MOBILE_MMS);
1001 addSupportedType(TYPE_MOBILE_SUPL);
1002 addSupportedType(TYPE_MOBILE_DUN);
1003 addSupportedType(TYPE_MOBILE_HIPRI);
1004 addSupportedType(TYPE_MOBILE_FOTA);
1005 addSupportedType(TYPE_MOBILE_IMS);
1006 addSupportedType(TYPE_MOBILE_CBS);
1007 addSupportedType(TYPE_MOBILE_IA);
1008 addSupportedType(TYPE_MOBILE_EMERGENCY);
1009 }
1010 if (pm.hasSystemFeature(FEATURE_BLUETOOTH)) {
1011 addSupportedType(TYPE_BLUETOOTH);
1012 }
1013 if (pm.hasSystemFeature(FEATURE_WATCH)) {
1014 // TYPE_PROXY is only used on Wear
1015 addSupportedType(TYPE_PROXY);
1016 }
1017 // Ethernet is often not specified in the configs, although many devices can use it via
1018 // USB host adapters. Add it as long as the ethernet service is here.
Xiao Ma0a171c02022-01-23 16:14:51 +00001019 if (deviceSupportsEthernet(ctx)) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001020 addSupportedType(TYPE_ETHERNET);
1021 }
1022
1023 // Always add TYPE_VPN as a supported type
1024 addSupportedType(TYPE_VPN);
1025 }
1026
1027 private void addSupportedType(int type) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001028 if (mTypeLists[type] != null) {
1029 throw new IllegalStateException(
1030 "legacy list for type " + type + "already initialized");
1031 }
Chalard Jeand6c33dc2018-06-04 13:33:12 +09001032 mTypeLists[type] = new ArrayList<>();
Robert Greenwalt802c1102014-06-02 15:32:02 -07001033 }
1034
Robert Greenwalt802c1102014-06-02 15:32:02 -07001035 public boolean isTypeSupported(int type) {
1036 return isNetworkTypeValid(type) && mTypeLists[type] != null;
1037 }
1038
1039 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi389633f2016-06-21 09:48:07 +09001040 synchronized (mTypeLists) {
1041 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
1042 return mTypeLists[type].get(0);
1043 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001044 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001045 return null;
Robert Greenwalt802c1102014-06-02 15:32:02 -07001046 }
1047
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001048 public int getRestoreTimerForType(int type) {
1049 synchronized (mTypeLists) {
1050 if (mRestoreTimers == null) {
1051 mRestoreTimers = loadRestoreTimers();
1052 }
1053 return mRestoreTimers.getOrDefault(type, -1);
1054 }
1055 }
1056
1057 private ArrayMap<Integer, Integer> loadRestoreTimers() {
1058 final String[] configs = mService.mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001059 R.array.config_legacy_networktype_restore_timers);
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001060 final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
1061 for (final String config : configs) {
1062 final String[] splits = TextUtils.split(config, ",");
1063 if (splits.length != 2) {
1064 logwtf("Invalid restore timer token count: " + config);
1065 continue;
1066 }
1067 try {
1068 ret.put(Integer.parseInt(splits[0]), Integer.parseInt(splits[1]));
1069 } catch (NumberFormatException e) {
1070 logwtf("Invalid restore timer number format: " + config, e);
1071 }
1072 }
1073 return ret;
1074 }
1075
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001076 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001077 boolean isDefaultNetwork) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001078 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09001079 log("Sending " + state
1080 + " broadcast for type " + type + " " + nai.toShortString()
Chalard Jean5b409c72021-02-04 13:12:59 +09001081 + " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001082 }
1083 }
1084
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001085 // When a lockdown VPN connects, send another CONNECTED broadcast for the underlying
1086 // network type, to preserve previous behaviour.
1087 private void maybeSendLegacyLockdownBroadcast(@NonNull NetworkAgentInfo vpnNai) {
1088 if (vpnNai != mService.getLegacyLockdownNai()) return;
1089
1090 if (vpnNai.declaredUnderlyingNetworks == null
1091 || vpnNai.declaredUnderlyingNetworks.length != 1) {
1092 Log.wtf(TAG, "Legacy lockdown VPN must have exactly one underlying network: "
1093 + Arrays.toString(vpnNai.declaredUnderlyingNetworks));
1094 return;
1095 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09001096 final NetworkAgentInfo underlyingNai = mService.getNetworkAgentInfoForNetwork(
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001097 vpnNai.declaredUnderlyingNetworks[0]);
1098 if (underlyingNai == null) return;
1099
1100 final int type = underlyingNai.networkInfo.getType();
1101 final DetailedState state = DetailedState.CONNECTED;
1102 maybeLogBroadcast(underlyingNai, state, type, true /* isDefaultNetwork */);
1103 mService.sendLegacyNetworkBroadcast(underlyingNai, state, type);
1104 }
1105
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001106 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt802c1102014-06-02 15:32:02 -07001107 public void add(int type, NetworkAgentInfo nai) {
1108 if (!isTypeSupported(type)) {
1109 return; // Invalid network type.
1110 }
1111 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
1112
1113 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1114 if (list.contains(nai)) {
Robert Greenwalt802c1102014-06-02 15:32:02 -07001115 return;
1116 }
Hugo Benichi389633f2016-06-21 09:48:07 +09001117 synchronized (mTypeLists) {
1118 list.add(nai);
1119 }
Lorenzo Colitti4b584062014-09-28 16:08:06 +09001120
Chalard Jean5b409c72021-02-04 13:12:59 +09001121 // Send a broadcast if this is the first network of its type or if it's the default.
1122 final boolean isDefaultNetwork = mService.isDefaultNetwork(nai);
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001123
1124 // If a legacy lockdown VPN is active, override the NetworkInfo state in all broadcasts
1125 // to preserve previous behaviour.
1126 final DetailedState state = mService.getLegacyLockdownState(DetailedState.CONNECTED);
Chalard Jean5b409c72021-02-04 13:12:59 +09001127 if ((list.size() == 1) || isDefaultNetwork) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09001128 maybeLogBroadcast(nai, state, type, isDefaultNetwork);
1129 mService.sendLegacyNetworkBroadcast(nai, state, type);
1130 }
1131
1132 if (type == TYPE_VPN && state == DetailedState.CONNECTED) {
1133 maybeSendLegacyLockdownBroadcast(nai);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001134 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001135 }
1136
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001137 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001138 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001139 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
1140 if (list == null || list.isEmpty()) {
1141 return;
1142 }
Lorenzo Colitti49767722015-05-01 00:30:10 +09001143 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001144
Hugo Benichi389633f2016-06-21 09:48:07 +09001145 synchronized (mTypeLists) {
1146 if (!list.remove(nai)) {
1147 return;
1148 }
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001149 }
1150
Lorenzo Colitti49767722015-05-01 00:30:10 +09001151 if (wasFirstNetwork || wasDefault) {
Chalard Jean37a2b462019-04-11 14:09:07 +09001152 maybeLogBroadcast(nai, DetailedState.DISCONNECTED, type, wasDefault);
1153 mService.sendLegacyNetworkBroadcast(nai, DetailedState.DISCONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001154 }
1155
1156 if (!list.isEmpty() && wasFirstNetwork) {
1157 if (DBG) log("Other network available for type " + type +
1158 ", sending connected broadcast");
Lorenzo Colitti49767722015-05-01 00:30:10 +09001159 final NetworkAgentInfo replacement = list.get(0);
Chalard Jean37a2b462019-04-11 14:09:07 +09001160 maybeLogBroadcast(replacement, DetailedState.CONNECTED, type,
Chalard Jean5b409c72021-02-04 13:12:59 +09001161 mService.isDefaultNetwork(replacement));
Chalard Jean37a2b462019-04-11 14:09:07 +09001162 mService.sendLegacyNetworkBroadcast(replacement, DetailedState.CONNECTED, type);
Lorenzo Colitticfb36572014-07-31 23:20:17 +09001163 }
1164 }
1165
1166 /** Removes the given network from all legacy type lists. */
Lorenzo Colitti49767722015-05-01 00:30:10 +09001167 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
1168 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001169 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti49767722015-05-01 00:30:10 +09001170 remove(type, nai, wasDefault);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001171 }
1172 }
Robert Greenwalt94e22142014-07-30 16:31:24 -07001173
Chalard Jean46bfbf02022-02-02 00:56:25 +09001174 // send out another legacy broadcast - currently only used for suspend/unsuspend toggle
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001175 public void update(NetworkAgentInfo nai) {
Chalard Jean5b409c72021-02-04 13:12:59 +09001176 final boolean isDefault = mService.isDefaultNetwork(nai);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001177 final DetailedState state = nai.networkInfo.getDetailedState();
1178 for (int type = 0; type < mTypeLists.length; type++) {
1179 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3df86c62015-07-10 16:00:36 -07001180 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi389633f2016-06-21 09:48:07 +09001181 final boolean isFirst = contains && (nai == list.get(0));
Chalard Jean5b409c72021-02-04 13:12:59 +09001182 if (isFirst || contains && isDefault) {
1183 maybeLogBroadcast(nai, state, type, isDefault);
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001184 mService.sendLegacyNetworkBroadcast(nai, state, type);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07001185 }
1186 }
1187 }
1188
Robert Greenwalt94e22142014-07-30 16:31:24 -07001189 public void dump(IndentingPrintWriter pw) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001190 pw.println("mLegacyTypeTracker:");
1191 pw.increaseIndent();
1192 pw.print("Supported types:");
Robert Greenwalt94e22142014-07-30 16:31:24 -07001193 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001194 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwalt94e22142014-07-30 16:31:24 -07001195 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001196 pw.println();
1197 pw.println("Current state:");
1198 pw.increaseIndent();
Hugo Benichi389633f2016-06-21 09:48:07 +09001199 synchronized (mTypeLists) {
1200 for (int type = 0; type < mTypeLists.length; type++) {
1201 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
1202 for (NetworkAgentInfo nai : mTypeLists[type]) {
Chalard Jean49707572019-12-10 21:07:02 +09001203 pw.println(type + " " + nai.toShortString());
Hugo Benichi389633f2016-06-21 09:48:07 +09001204 }
Lorenzo Colitti3b1ad962015-06-03 11:18:24 +09001205 }
1206 }
1207 pw.decreaseIndent();
1208 pw.decreaseIndent();
1209 pw.println();
Robert Greenwalt94e22142014-07-30 16:31:24 -07001210 }
Robert Greenwalt802c1102014-06-02 15:32:02 -07001211 }
Chalard Jean3a3f5f22019-04-10 23:07:55 +09001212 private final LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker(this);
Robert Greenwalt802c1102014-06-02 15:32:02 -07001213
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001214 final LocalPriorityDump mPriorityDumper = new LocalPriorityDump();
Vishnu Nair0701e422017-10-26 10:08:50 -07001215 /**
1216 * Helper class which parses out priority arguments and dumps sections according to their
1217 * priority. If priority arguments are omitted, function calls the legacy dump command.
1218 */
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001219 private class LocalPriorityDump {
1220 private static final String PRIORITY_ARG = "--dump-priority";
1221 private static final String PRIORITY_ARG_HIGH = "HIGH";
1222 private static final String PRIORITY_ARG_NORMAL = "NORMAL";
1223
1224 LocalPriorityDump() {}
1225
1226 private void dumpHigh(FileDescriptor fd, PrintWriter pw) {
1227 doDump(fd, pw, new String[] {DIAG_ARG});
1228 doDump(fd, pw, new String[] {SHORT_ARG});
Vishnu Nair0701e422017-10-26 10:08:50 -07001229 }
1230
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001231 private void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args) {
1232 doDump(fd, pw, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07001233 }
1234
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001235 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1236 if (args == null) {
1237 dumpNormal(fd, pw, args);
1238 return;
1239 }
1240
1241 String priority = null;
1242 for (int argIndex = 0; argIndex < args.length; argIndex++) {
1243 if (args[argIndex].equals(PRIORITY_ARG) && argIndex + 1 < args.length) {
1244 argIndex++;
1245 priority = args[argIndex];
1246 }
1247 }
1248
1249 if (PRIORITY_ARG_HIGH.equals(priority)) {
1250 dumpHigh(fd, pw);
1251 } else if (PRIORITY_ARG_NORMAL.equals(priority)) {
1252 dumpNormal(fd, pw, args);
1253 } else {
1254 // ConnectivityService publishes binder service using publishBinderService() with
1255 // no priority assigned will be treated as NORMAL priority. Dumpsys does not send
Chiachang Wang05fbb452021-05-17 16:57:15 +08001256 // "--dump-priority" arguments to the service. Thus, dump NORMAL only to align the
1257 // legacy output for dumpsys connectivity.
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001258 // TODO: Integrate into signal dump.
1259 dumpNormal(fd, pw, args);
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001260 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001261 }
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08001262 }
Vishnu Nair0701e422017-10-26 10:08:50 -07001263
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001264 /**
1265 * Dependencies of ConnectivityService, for injection in tests.
1266 */
1267 @VisibleForTesting
1268 public static class Dependencies {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09001269 public int getCallingUid() {
1270 return Binder.getCallingUid();
1271 }
1272
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001273 /**
1274 * Get system properties to use in ConnectivityService.
1275 */
1276 public MockableSystemProperties getSystemProperties() {
1277 return new MockableSystemProperties();
1278 }
1279
1280 /**
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001281 * Get the {@link ConnectivityResources} to use in ConnectivityService.
1282 */
1283 public ConnectivityResources getResources(@NonNull Context ctx) {
1284 return new ConnectivityResources(ctx);
1285 }
1286
1287 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001288 * Create a HandlerThread to use in ConnectivityService.
1289 */
1290 public HandlerThread makeHandlerThread() {
1291 return new HandlerThread("ConnectivityServiceThread");
1292 }
1293
1294 /**
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001295 * Get a reference to the ModuleNetworkStackClient.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001296 */
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001297 public NetworkStackClientBase getNetworkStack() {
1298 return ModuleNetworkStackClient.getInstance(null);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001299 }
1300
1301 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001302 * @see ProxyTracker
1303 */
1304 public ProxyTracker makeProxyTracker(@NonNull Context context,
1305 @NonNull Handler connServiceHandler) {
1306 return new ProxyTracker(context, connServiceHandler, EVENT_PROXY_HAS_CHANGED);
1307 }
1308
1309 /**
1310 * @see NetIdManager
1311 */
1312 public NetIdManager makeNetIdManager() {
1313 return new NetIdManager();
1314 }
1315
1316 /**
1317 * @see NetworkUtils#queryUserAccess(int, int)
1318 */
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09001319 public boolean queryUserAccess(int uid, Network network, ConnectivityService cs) {
1320 return cs.queryUserAccess(uid, network);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001321 }
1322
1323 /**
Lorenzo Colitti3be9df12021-02-04 01:47:38 +09001324 * Gets the UID that owns a socket connection. Needed because opening SOCK_DIAG sockets
1325 * requires CAP_NET_ADMIN, which the unit tests do not have.
1326 */
1327 public int getConnectionOwnerUid(int protocol, InetSocketAddress local,
1328 InetSocketAddress remote) {
1329 return InetDiagMessage.getConnectionOwnerUid(protocol, local, remote);
1330 }
1331
1332 /**
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001333 * @see MultinetworkPolicyTracker
1334 */
1335 public MultinetworkPolicyTracker makeMultinetworkPolicyTracker(
1336 @NonNull Context c, @NonNull Handler h, @NonNull Runnable r) {
1337 return new MultinetworkPolicyTracker(c, h, r);
1338 }
1339
Aaron Huang330a4c02020-10-27 03:36:19 +08001340 /**
chiachangwang7c17c282023-02-02 05:58:59 +00001341 * @see AutomaticOnOffKeepaliveTracker
1342 */
1343 public AutomaticOnOffKeepaliveTracker makeAutomaticOnOffKeepaliveTracker(
1344 @NonNull Context c, @NonNull Handler h) {
1345 return new AutomaticOnOffKeepaliveTracker(c, h);
1346 }
1347
1348 /**
Aaron Huang330a4c02020-10-27 03:36:19 +08001349 * @see BatteryStatsManager
1350 */
1351 public void reportNetworkInterfaceForTransports(Context context, String iface,
1352 int[] transportTypes) {
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001353 final BatteryStatsManager batteryStats =
Aaron Huang330a4c02020-10-27 03:36:19 +08001354 context.getSystemService(BatteryStatsManager.class);
1355 batteryStats.reportNetworkInterfaceForTransports(iface, transportTypes);
1356 }
Lorenzo Colitti9b8b90b2021-03-10 16:39:18 +09001357
1358 public boolean getCellular464XlatEnabled() {
1359 return NetworkProperties.isCellular464XlatEnabled().orElse(true);
1360 }
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001361
1362 /**
1363 * @see PendingIntent#intentFilterEquals
1364 */
1365 public boolean intentFilterEquals(PendingIntent a, PendingIntent b) {
1366 return a.intentFilterEquals(b);
1367 }
1368
1369 /**
1370 * @see LocationPermissionChecker
1371 */
1372 public LocationPermissionChecker makeLocationPermissionChecker(Context context) {
1373 return new LocationPermissionChecker(context);
1374 }
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001375
1376 /**
Chalard Jeanac9ace02022-01-26 16:54:05 +09001377 * @see CarrierPrivilegeAuthenticator
Chalard Jean46bfbf02022-02-02 00:56:25 +09001378 *
1379 * This method returns null in versions before T, where carrier privilege
1380 * authentication is not supported.
Chalard Jeanac9ace02022-01-26 16:54:05 +09001381 */
Chalard Jean46bfbf02022-02-02 00:56:25 +09001382 @Nullable
Chalard Jeanac9ace02022-01-26 16:54:05 +09001383 public CarrierPrivilegeAuthenticator makeCarrierPrivilegeAuthenticator(
1384 @NonNull final Context context, @NonNull final TelephonyManager tm) {
1385 if (SdkLevel.isAtLeastT()) {
1386 return new CarrierPrivilegeAuthenticator(context, tm);
1387 } else {
1388 return null;
1389 }
1390 }
1391
1392 /**
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001393 * @see DeviceConfigUtils#isFeatureEnabled
1394 */
1395 public boolean isFeatureEnabled(Context context, String name, boolean defaultEnabled) {
1396 return DeviceConfigUtils.isFeatureEnabled(context, NAMESPACE_CONNECTIVITY, name,
1397 TETHERING_MODULE_NAME, defaultEnabled);
1398 }
Wayne Ma2fde98c2022-01-17 18:04:05 +08001399
1400 /**
1401 * Get the BpfNetMaps implementation to use in ConnectivityService.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001402 * @param netd a netd binder
Wayne Ma2fde98c2022-01-17 18:04:05 +08001403 * @return BpfNetMaps implementation.
1404 */
Motomu Utsumif688eeb2022-07-22 03:47:35 +00001405 public BpfNetMaps getBpfNetMaps(Context context, INetd netd) {
1406 return new BpfNetMaps(context, netd);
Wayne Ma2fde98c2022-01-17 18:04:05 +08001407 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001408
1409 /**
Hungming Cheneb15a2d2022-01-16 15:15:57 +08001410 * @see ClatCoordinator
1411 */
1412 public ClatCoordinator getClatCoordinator(INetd netd) {
1413 return new ClatCoordinator(
1414 new ClatCoordinator.Dependencies() {
1415 @NonNull
1416 public INetd getNetd() {
1417 return netd;
1418 }
1419 });
1420 }
1421
1422 /**
Patrick Rohr2857ac42022-01-21 14:58:16 +01001423 * Wraps {@link TcUtils#tcFilterAddDevIngressPolice}
1424 */
1425 public void enableIngressRateLimit(String iface, long rateInBytesPerSecond) {
1426 final InterfaceParams params = InterfaceParams.getByName(iface);
1427 if (params == null) {
1428 // the interface might have disappeared.
1429 logw("Failed to get interface params for interface " + iface);
1430 return;
1431 }
1432 try {
1433 // converting rateInBytesPerSecond from long to int is safe here because the
1434 // setting's range is limited to INT_MAX.
1435 // TODO: add long/uint64 support to tcFilterAddDevIngressPolice.
Patrick Rohr64592df2022-02-10 15:19:31 +01001436 Log.i(TAG,
1437 "enableIngressRateLimit on " + iface + ": " + rateInBytesPerSecond + "B/s");
Patrick Rohr2857ac42022-01-21 14:58:16 +01001438 TcUtils.tcFilterAddDevIngressPolice(params.index, TC_PRIO_POLICE, (short) ETH_P_ALL,
1439 (int) rateInBytesPerSecond, TC_POLICE_BPF_PROG_PATH);
1440 } catch (IOException e) {
1441 loge("TcUtils.tcFilterAddDevIngressPolice(ifaceIndex=" + params.index
1442 + ", PRIO_POLICE, ETH_P_ALL, rateInBytesPerSecond="
1443 + rateInBytesPerSecond + ", bpfProgPath=" + TC_POLICE_BPF_PROG_PATH
1444 + ") failure: ", e);
1445 }
1446 }
1447
1448 /**
1449 * Wraps {@link TcUtils#tcFilterDelDev}
1450 */
1451 public void disableIngressRateLimit(String iface) {
1452 final InterfaceParams params = InterfaceParams.getByName(iface);
1453 if (params == null) {
1454 // the interface might have disappeared.
1455 logw("Failed to get interface params for interface " + iface);
1456 return;
1457 }
1458 try {
Patrick Rohr64592df2022-02-10 15:19:31 +01001459 Log.i(TAG,
1460 "disableIngressRateLimit on " + iface);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001461 TcUtils.tcFilterDelDev(params.index, true, TC_PRIO_POLICE, (short) ETH_P_ALL);
1462 } catch (IOException e) {
1463 loge("TcUtils.tcFilterDelDev(ifaceIndex=" + params.index
1464 + ", ingress=true, PRIO_POLICE, ETH_P_ALL) failure: ", e);
1465 }
1466 }
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08001467
1468 /**
1469 * Wraps {@link BroadcastOptionsShimImpl#newInstance(BroadcastOptions)}
1470 */
1471 // TODO: when available in all active branches:
1472 // @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
1473 @RequiresApi(Build.VERSION_CODES.CUR_DEVELOPMENT)
1474 public BroadcastOptionsShim makeBroadcastOptionsShim(BroadcastOptions options) {
1475 return BroadcastOptionsShimImpl.newInstance(options);
1476 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09001477
1478 /**
1479 * Wrapper method for
1480 * {@link android.app.compat.CompatChanges#isChangeEnabled(long, String, UserHandle)}.
1481 *
1482 * @param changeId The ID of the compatibility change in question.
1483 * @param packageName The package name of the app in question.
1484 * @param user The user that the operation is done for.
1485 * @return {@code true} if the change is enabled for the specified package.
1486 */
1487 public boolean isChangeEnabled(long changeId, @NonNull final String packageName,
1488 @NonNull final UserHandle user) {
1489 return CompatChanges.isChangeEnabled(changeId, packageName, user);
1490 }
Motomu Utsumi93a22182023-03-16 17:04:21 +09001491
1492 /**
1493 * Call {@link InetDiagMessage#destroyLiveTcpSockets(Set, Set)}
1494 *
1495 * @param ranges target uid ranges
1496 * @param exemptUids uids to skip close socket
1497 */
1498 public void destroyLiveTcpSockets(@NonNull final Set<Range<Integer>> ranges,
1499 @NonNull final Set<Integer> exemptUids)
1500 throws SocketException, InterruptedIOException, ErrnoException {
1501 InetDiagMessage.destroyLiveTcpSockets(ranges, exemptUids);
1502 }
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001503 }
1504
junyulaie7c7d2a2021-01-26 15:29:15 +08001505 public ConnectivityService(Context context) {
1506 this(context, getDnsResolver(context), new IpConnectivityLog(),
Remi NGUYEN VAN8ae54f72021-03-06 00:26:43 +09001507 INetd.Stub.asInterface((IBinder) context.getSystemService(Context.NETD_SERVICE)),
1508 new Dependencies());
Hugo Benichi208c0102016-07-28 17:53:06 +09001509 }
1510
1511 @VisibleForTesting
junyulaie7c7d2a2021-01-26 15:29:15 +08001512 protected ConnectivityService(Context context, IDnsResolver dnsresolver,
1513 IpConnectivityLog logger, INetd netd, Dependencies deps) {
Wink Savillee70c6f52010-12-03 12:01:38 -08001514 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltd48f8ee2010-01-14 17:47:58 -08001515
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001516 mDeps = Objects.requireNonNull(deps, "missing Dependencies");
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09001517 mFlags = new ConnectivityFlags();
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001518 mSystemProperties = mDeps.getSystemProperties();
1519 mNetIdManager = mDeps.makeNetIdManager();
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001520 mContext = Objects.requireNonNull(context, "missing Context");
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09001521 mResources = deps.getResources(mContext);
Junyu Lai00d92df2022-07-05 11:01:52 +08001522 // The legacy PerUidCounter is buggy and throwing exception at count == limit.
1523 // Pass limit - 1 to maintain backward compatibility.
1524 // TODO: Remove the workaround.
1525 mNetworkRequestCounter =
1526 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_UID - 1);
1527 mSystemNetworkRequestCounter =
1528 new RequestInfoPerUidCounter(MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1);
Lorenzo Colitticd447b22017-03-21 18:54:11 +09001529
Hugo Benichi208c0102016-07-28 17:53:06 +09001530 mMetricsLog = logger;
James Mattis45d81842021-01-10 14:24:24 -08001531 final NetworkRequest defaultInternetRequest = createDefaultRequest();
1532 mDefaultRequest = new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09001533 Process.myUid(), defaultInternetRequest, null,
Chalard Jeana3578a52021-10-25 19:24:48 +09001534 null /* binder */, NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001535 null /* attributionTags */);
Chalard Jean5b409c72021-02-04 13:12:59 +09001536 mNetworkRequests.put(defaultInternetRequest, mDefaultRequest);
1537 mDefaultNetworkRequests.add(mDefaultRequest);
1538 mNetworkRequestInfoLogs.log("REGISTER " + mDefaultRequest);
Erik Kline05f2b402015-04-30 12:58:40 +09001539
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001540 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001541 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07001542
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001543 // The default WiFi request is a background request so that apps using WiFi are
1544 // migrated to a better network (typically ethernet) when one comes up, instead
1545 // of staying on WiFi forever.
1546 mDefaultWifiRequest = createDefaultInternetRequestForTransport(
1547 NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
1548
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001549 mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
1550 NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
1551 NetworkRequest.Type.BACKGROUND_REQUEST);
1552
Chalard Jean0702f982021-09-16 21:50:07 +09001553 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
1554 // TODO: Consider making the timer customizable.
1555 mNascentDelayMs = DEFAULT_NASCENT_DELAY_MS;
1556 mCellularRadioTimesharingCapable =
1557 mResources.get().getBoolean(R.bool.config_cellular_radio_timesharing_capable);
1558
Paul Hu51f816b2022-08-11 14:43:47 +00001559 mNetd = netd;
1560 mBpfNetMaps = mDeps.getBpfNetMaps(mContext, netd);
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001561 mHandlerThread = mDeps.makeHandlerThread();
Paul Hu51f816b2022-08-11 14:43:47 +00001562 mPermissionMonitor =
1563 new PermissionMonitor(mContext, mNetd, mBpfNetMaps, mHandlerThread);
Lorenzo Colitti0891bc42015-08-07 20:17:27 +09001564 mHandlerThread.start();
1565 mHandler = new InternalHandler(mHandlerThread.getLooper());
1566 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Cody Kesting73708bf2019-12-18 10:57:50 -08001567 mConnectivityDiagnosticsHandler =
1568 new ConnectivityDiagnosticsHandler(mHandlerThread.getLooper());
Wink Saville775aad62010-09-02 19:23:52 -07001569
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001570 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001571 ConnectivitySettingsManager.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08001572
junyulaie7c7d2a2021-01-26 15:29:15 +08001573 mStatsManager = mContext.getSystemService(NetworkStatsManager.class);
paulhu9a9f71b2020-12-29 18:15:13 +08001574 mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
Daulet Zhanguzinee674252020-03-26 12:30:39 +00001575 mDnsResolver = Objects.requireNonNull(dnsresolver, "missing IDnsResolver");
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001576 mProxyTracker = mDeps.makeProxyTracker(mContext, mHandler);
Hugo Benichi39621362017-02-11 17:04:43 +09001577
Wink Saville32506bc2013-06-29 21:10:57 -07001578 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08001579 mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09001580 mLocationPermissionChecker = mDeps.makeLocationPermissionChecker(mContext);
Chalard Jeanac9ace02022-01-26 16:54:05 +09001581 mCarrierPrivilegeAuthenticator =
1582 mDeps.makeCarrierPrivilegeAuthenticator(mContext, mTelephonyManager);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001583
Sudheer Shanka9967d462021-03-18 19:09:25 +00001584 // To ensure uid state is synchronized with Network Policy, register for
junyulaif2c67e42018-08-07 19:50:45 +08001585 // NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
1586 // reading existing policy from disk.
Sudheer Shanka9967d462021-03-18 19:09:25 +00001587 mPolicyManager.registerNetworkPolicyCallback(null, mPolicyCallback);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001588
1589 final PowerManager powerManager = (PowerManager) context.getSystemService(
1590 Context.POWER_SERVICE);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001591 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08001592 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07001593
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001594 mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
1595 mProtectedNetworks = new ArrayList<>();
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001596 int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001597 for (int p : protectedNetworks) {
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09001598 if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
Robert Greenwalt6cac0742011-06-21 17:26:14 -07001599 mProtectedNetworks.add(p);
1600 } else {
1601 if (DBG) loge("Ignoring protectedNetwork " + p);
1602 }
1603 }
1604
soma, kawata29444ae2019-05-23 09:30:40 +09001605 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
1606
James Mattis02220e22021-03-13 19:27:21 -08001607 mUserAllContext = mContext.createContextAsUser(UserHandle.ALL, 0 /* flags */);
Lorenzo Colitticd675292021-02-04 17:32:07 +09001608 // Listen for user add/removes to inform PermissionMonitor.
Varun Ananddf569952019-02-06 10:13:38 -08001609 // Should run on mHandler to avoid any races.
James Mattis02220e22021-03-13 19:27:21 -08001610 final IntentFilter userIntentFilter = new IntentFilter();
1611 userIntentFilter.addAction(Intent.ACTION_USER_ADDED);
1612 userIntentFilter.addAction(Intent.ACTION_USER_REMOVED);
1613 mUserAllContext.registerReceiver(mUserIntentReceiver, userIntentFilter,
1614 null /* broadcastPermission */, mHandler);
paulhuedd411a2020-10-13 15:56:13 +08001615
James Mattis02220e22021-03-13 19:27:21 -08001616 // Listen to package add/removes for netd
1617 final IntentFilter packageIntentFilter = new IntentFilter();
1618 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1619 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1620 packageIntentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
1621 packageIntentFilter.addDataScheme("package");
1622 mUserAllContext.registerReceiver(mPackageIntentReceiver, packageIntentFilter,
Lorenzo Colitticd675292021-02-04 17:32:07 +09001623 null /* broadcastPermission */, mHandler);
junyulaid91e7052020-08-28 13:44:33 +08001624
lucaslind5c2d072021-02-20 18:59:47 +08001625 mNetworkActivityTracker = new LegacyNetworkActivityTracker(mContext, mHandler, mNetd);
Chia-chi Yehf3204aa2011-05-23 15:08:29 -07001626
Chalard Jean46bfbf02022-02-02 00:56:25 +09001627 final NetdCallback netdCallback = new NetdCallback();
lucaslin66f44212021-02-23 01:12:55 +08001628 try {
Chalard Jean46bfbf02022-02-02 00:56:25 +09001629 mNetd.registerUnsolicitedEventListener(netdCallback);
lucaslin66f44212021-02-23 01:12:55 +08001630 } catch (RemoteException | ServiceSpecificException e) {
1631 loge("Error registering event listener :" + e);
1632 }
1633
Erik Kline05f2b402015-04-30 12:58:40 +09001634 mSettingsObserver = new SettingsObserver(mContext, mHandler);
1635 registerSettingsCallbacks();
Robert Greenwalt6f7c6092010-12-02 11:31:00 -08001636
chiachangwang7c17c282023-02-02 05:58:59 +00001637 mKeepaliveTracker = mDeps.makeAutomaticOnOffKeepaliveTracker(mContext, mHandler);
paulhu539aa9a2020-10-14 09:51:54 +08001638 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager);
Daniel Brightf9e945b2020-06-15 16:10:01 -07001639 mQosCallbackTracker = new QosCallbackTracker(mHandler, mNetworkRequestCounter);
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001640
1641 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001642 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001643 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
1644 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08001645 ConnectivitySettingsManager.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
Lorenzo Colitti9bf6fef2016-08-29 14:03:11 +09001646 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
1647 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti21924542016-09-16 23:43:38 +09001648
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09001649 mMultinetworkPolicyTracker = mDeps.makeMultinetworkPolicyTracker(
Chalard Jeanf3ff3622021-03-19 13:49:56 +09001650 mContext, mHandler, () -> updateAvoidBadWifi());
Chalard Jean020b93a2022-09-01 13:20:14 +09001651 mNetworkRanker =
1652 new NetworkRanker(new NetworkRanker.Configuration(activelyPreferBadWifi()));
1653
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09001654 mMultinetworkPolicyTracker.start();
Erik Kline32120082017-12-13 19:40:49 +09001655
Chiachang Wangc1215d32020-10-20 15:38:58 +08001656 mDnsManager = new DnsManager(mContext, mDnsResolver);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001657 registerPrivateDnsSettingsCallbacks();
James Mattisd31bdfa2020-12-23 16:37:26 -08001658
Chalard Jean28018572020-12-21 18:36:52 +09001659 // This NAI is a sentinel used to offer no service to apps that are on a multi-layer
1660 // request that doesn't allow fallback to the default network. It should never be visible
1661 // to apps. As such, it's not in the list of NAIs and doesn't need many of the normal
1662 // arguments like the handler or the DnsResolver.
1663 // TODO : remove this ; it is probably better handled with a sentinel request.
lucaslind5c2d072021-02-20 18:59:47 +08001664 mNoServiceNetwork = new NetworkAgentInfo(null,
Ken Chen75c6d332021-05-14 14:30:43 +08001665 new Network(INetd.UNREACHABLE_NET_ID),
James Mattisd31bdfa2020-12-23 16:37:26 -08001666 new NetworkInfo(TYPE_NONE, 0, "", ""),
Chalard Jean28018572020-12-21 18:36:52 +09001667 new LinkProperties(), new NetworkCapabilities(),
1668 new NetworkScore.Builder().setLegacyInt(0).build(), mContext, null,
Chalard Jean550b5212021-03-05 23:07:53 +09001669 new NetworkAgentConfig(), this, null, null, 0, INVALID_UID,
1670 mLingerDelayMs, mQosCallbackTracker, mDeps);
Tyler Wear72388212021-09-09 14:49:02 -07001671
1672 try {
Lorenzo Colittidebd9ea2022-01-27 23:02:59 +09001673 // DscpPolicyTracker cannot run on S because on S the tethering module can only load
1674 // BPF programs/maps into /sys/fs/tethering/bpf, which the system server cannot access.
1675 // Even if it could, running on S would at least require mocking out the BPF map,
1676 // otherwise the unit tests will fail on pre-T devices where the seccomp filter blocks
1677 // the bpf syscall. http://aosp/1907693
1678 if (SdkLevel.isAtLeastT()) {
1679 mDscpPolicyTracker = new DscpPolicyTracker();
1680 }
Tyler Wear72388212021-09-09 14:49:02 -07001681 } catch (ErrnoException e) {
1682 loge("Unable to create DscpPolicyTracker");
1683 }
Patrick Rohr2857ac42022-01-21 14:58:16 +01001684
1685 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
1686 mContext);
Igor Chernyshev9dac6602022-12-13 19:28:32 -08001687
1688 if (SdkLevel.isAtLeastT()) {
1689 mCdmps = new CompanionDeviceManagerProxyService(context);
1690 } else {
1691 mCdmps = null;
1692 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08001693 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07001694
Xiao Ma0a171c02022-01-23 16:14:51 +00001695 /**
1696 * Check whether or not the device supports Ethernet transport.
1697 */
1698 public static boolean deviceSupportsEthernet(final Context context) {
1699 final PackageManager pm = context.getPackageManager();
1700 return pm.hasSystemFeature(PackageManager.FEATURE_ETHERNET)
1701 || pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
1702 }
1703
Chalard Jean46adcf32018-04-18 20:18:38 +09001704 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUid(int uid) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001705 return createDefaultNetworkCapabilitiesForUidRangeSet(Collections.singleton(
1706 new UidRange(uid, uid)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +09001707 }
1708
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001709 private static NetworkCapabilities createDefaultNetworkCapabilitiesForUidRangeSet(
1710 @NonNull final Set<UidRange> uidRangeSet) {
Chalard Jean46adcf32018-04-18 20:18:38 +09001711 final NetworkCapabilities netCap = new NetworkCapabilities();
1712 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001713 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Chalard Jean46adcf32018-04-18 20:18:38 +09001714 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Sooraj Sasindran499117f2021-11-29 12:40:09 -08001715 netCap.setUids(UidRange.toIntRanges(uidRangeSet));
Chalard Jean46adcf32018-04-18 20:18:38 +09001716 return netCap;
1717 }
1718
James Mattis45d81842021-01-10 14:24:24 -08001719 private NetworkRequest createDefaultRequest() {
1720 return createDefaultInternetRequestForTransport(
1721 TYPE_NONE, NetworkRequest.Type.REQUEST);
1722 }
1723
lucaslin3ba7cc22022-12-19 02:35:33 +00001724 private NetworkRequest createVpnRequest() {
1725 final NetworkCapabilities netCap = new NetworkCapabilities.Builder()
1726 .withoutDefaultCapabilities()
1727 .addTransportType(TRANSPORT_VPN)
1728 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1729 .addCapability(NET_CAPABILITY_NOT_RESTRICTED)
1730 .build();
1731 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1732 return createNetworkRequest(NetworkRequest.Type.REQUEST, netCap);
1733 }
1734
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09001735 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001736 int transportType, NetworkRequest.Type type) {
Erik Klinea34b5842018-06-14 17:36:40 +09001737 final NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colittie14a6222015-05-14 17:07:20 +09001738 netCap.addCapability(NET_CAPABILITY_INTERNET);
junyulai719814c2021-01-13 18:13:11 +08001739 netCap.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
Roshan Pius08c94fb2020-01-16 12:17:17 -08001740 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
James Mattis45d81842021-01-10 14:24:24 -08001741 if (transportType > TYPE_NONE) {
Erik Kline05f2b402015-04-30 12:58:40 +09001742 netCap.addTransportType(transportType);
1743 }
James Mattis45d81842021-01-10 14:24:24 -08001744 return createNetworkRequest(type, netCap);
1745 }
1746
1747 private NetworkRequest createNetworkRequest(
1748 NetworkRequest.Type type, NetworkCapabilities netCap) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09001749 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Kline05f2b402015-04-30 12:58:40 +09001750 }
1751
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001752 private NetworkRequest createAlwaysOnRequestForCapability(int capability,
1753 NetworkRequest.Type type) {
1754 final NetworkCapabilities netCap = new NetworkCapabilities();
1755 netCap.clearAll();
1756 netCap.addCapability(capability);
1757 netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
1758 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
1759 }
1760
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001761 // Used only for testing.
1762 // TODO: Delete this and either:
Erik Kline9a62f012018-03-21 07:18:33 -07001763 // 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001764 // changing ContentResolver to make registerContentObserver non-final).
1765 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
1766 // by subclassing SettingsObserver.
1767 @VisibleForTesting
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001768 void updateAlwaysOnNetworks() {
1769 mHandler.sendEmptyMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
Lorenzo Colitti9fc66e02016-06-05 21:00:23 +09001770 }
1771
Erik Kline9a62f012018-03-21 07:18:33 -07001772 // See FakeSettingsProvider comment above.
1773 @VisibleForTesting
1774 void updatePrivateDnsSettings() {
1775 mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
1776 }
1777
paulhu51f77dc2021-06-07 02:34:20 +00001778 @VisibleForTesting
1779 void updateMobileDataPreferredUids() {
1780 mHandler.sendEmptyMessage(EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
1781 }
1782
Patrick Rohr2857ac42022-01-21 14:58:16 +01001783 @VisibleForTesting
1784 void updateIngressRateLimit() {
1785 mHandler.sendEmptyMessage(EVENT_INGRESS_RATE_LIMIT_CHANGED);
1786 }
1787
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001788 private void handleAlwaysOnNetworkRequest(
1789 NetworkRequest networkRequest, String settingName, boolean defaultValue) {
Hugo Benichif4210292017-04-21 15:07:12 +09001790 final boolean enable = toBool(Settings.Global.getInt(
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001791 mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08001792 handleAlwaysOnNetworkRequest(networkRequest, enable);
1793 }
1794
1795 private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001796 final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
Erik Kline05f2b402015-04-30 12:58:40 +09001797 if (enable == isEnabled) {
1798 return; // Nothing to do.
1799 }
1800
1801 if (enable) {
1802 handleRegisterNetworkRequest(new NetworkRequestInfo(
Chalard Jeana3578a52021-10-25 19:24:48 +09001803 Process.myUid(), networkRequest, null /* messenger */, null /* binder */,
Roshan Pius951c0032020-12-22 15:10:42 -08001804 NetworkCallback.FLAG_INCLUDE_LOCATION_INFO,
James Mattis45d81842021-01-10 14:24:24 -08001805 null /* attributionTags */));
Erik Kline05f2b402015-04-30 12:58:40 +09001806 } else {
Etan Cohenfbfdd842019-01-08 12:09:18 -08001807 handleReleaseNetworkRequest(networkRequest, Process.SYSTEM_UID,
1808 /* callOnUnavailable */ false);
Erik Kline05f2b402015-04-30 12:58:40 +09001809 }
1810 }
1811
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001812 private void handleConfigureAlwaysOnNetworks() {
paulhu56e09df2021-03-17 20:30:33 +08001813 handleAlwaysOnNetworkRequest(mDefaultMobileDataRequest,
1814 ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
1815 handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
1816 ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09001817 final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
1818 R.bool.config_vehicleInternalNetworkAlwaysRequested);
Remi NGUYEN VAN14233472021-05-19 12:05:13 +09001819 handleAlwaysOnNetworkRequest(mDefaultVehicleRequest, vehicleAlwaysRequested);
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001820 }
1821
paulhu51f77dc2021-06-07 02:34:20 +00001822 // Note that registering observer for setting do not get initial callback when registering,
paulhu01f52e72021-05-26 12:22:38 +08001823 // callers must fetch the initial value of the setting themselves if needed.
Erik Kline05f2b402015-04-30 12:58:40 +09001824 private void registerSettingsCallbacks() {
1825 // Watch for global HTTP proxy changes.
1826 mSettingsObserver.observe(
1827 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
1828 EVENT_APPLY_GLOBAL_HTTP_PROXY);
1829
Chalard Jean46bfbf02022-02-02 00:56:25 +09001830 // Watch for whether to keep mobile data always on.
Erik Kline05f2b402015-04-30 12:58:40 +09001831 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001832 Settings.Global.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001833 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
1834
Chalard Jean46bfbf02022-02-02 00:56:25 +09001835 // Watch for whether to keep wifi always on.
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001836 mSettingsObserver.observe(
paulhu56e09df2021-03-17 20:30:33 +08001837 Settings.Global.getUriFor(ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED),
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07001838 EVENT_CONFIGURE_ALWAYS_ON_NETWORKS);
paulhu51f77dc2021-06-07 02:34:20 +00001839
1840 // Watch for mobile data preferred uids changes.
1841 mSettingsObserver.observe(
1842 Settings.Secure.getUriFor(ConnectivitySettingsManager.MOBILE_DATA_PREFERRED_UIDS),
1843 EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED);
Patrick Rohr2857ac42022-01-21 14:58:16 +01001844
1845 // Watch for ingress rate limit changes.
1846 mSettingsObserver.observe(
Patrick Rohrcdac7492022-02-10 15:13:29 +01001847 Settings.Global.getUriFor(
Patrick Rohr2857ac42022-01-21 14:58:16 +01001848 ConnectivitySettingsManager.INGRESS_RATE_LIMIT_BYTES_PER_SECOND),
1849 EVENT_INGRESS_RATE_LIMIT_CHANGED);
Erik Kline05f2b402015-04-30 12:58:40 +09001850 }
1851
Erik Kline31b4a9e2018-01-11 21:07:29 +09001852 private void registerPrivateDnsSettingsCallbacks() {
Erik Kline9a62f012018-03-21 07:18:33 -07001853 for (Uri uri : DnsManager.getPrivateDnsSettingsUris()) {
1854 mSettingsObserver.observe(uri, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
Erik Kline31b4a9e2018-01-11 21:07:29 +09001855 }
1856 }
1857
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001858 private synchronized int nextNetworkRequestId() {
junyulai70afb0c2020-12-14 18:51:02 +08001859 // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
1860 // doing that.
Robert Greenwalt0eb55c12014-05-18 16:22:10 -07001861 return mNextNetworkRequestId++;
1862 }
1863
junyulai74f9a8b2018-06-13 15:00:37 +08001864 @VisibleForTesting
Chalard Jean46bfbf02022-02-02 00:56:25 +09001865 @Nullable
junyulai74f9a8b2018-06-13 15:00:37 +08001866 protected NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001867 if (network == null) {
1868 return null;
1869 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08001870 return getNetworkAgentInfoForNetId(network.getNetId());
Erik Kline9a62f012018-03-21 07:18:33 -07001871 }
1872
1873 private NetworkAgentInfo getNetworkAgentInfoForNetId(int netId) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001874 synchronized (mNetworkForNetId) {
Erik Kline9a62f012018-03-21 07:18:33 -07001875 return mNetworkForNetId.get(netId);
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001876 }
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001877 }
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08001878
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001879 // TODO: determine what to do when more than one VPN applies to |uid|.
Chalard Jean46bfbf02022-02-02 00:56:25 +09001880 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001881 private NetworkAgentInfo getVpnForUid(int uid) {
1882 synchronized (mNetworkForNetId) {
1883 for (int i = 0; i < mNetworkForNetId.size(); i++) {
1884 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
Chalard Jean254bd162022-08-25 13:04:51 +09001885 if (nai.isVPN() && nai.everConnected()
1886 && nai.networkCapabilities.appliesToUid(uid)) {
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001887 return nai;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001888 }
1889 }
1890 }
1891 return null;
1892 }
1893
Chalard Jean46bfbf02022-02-02 00:56:25 +09001894 @Nullable
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001895 private Network[] getVpnUnderlyingNetworks(int uid) {
Lorenzo Colitticd675292021-02-04 17:32:07 +09001896 if (mLockdownEnabled) return null;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001897 final NetworkAgentInfo nai = getVpnForUid(uid);
1898 if (nai != null) return nai.declaredUnderlyingNetworks;
1899 return null;
1900 }
1901
Lorenzo Colittia7574052021-01-19 01:33:05 +09001902 private NetworkAgentInfo getNetworkAgentInfoForUid(int uid) {
James Mattis2516da32021-01-31 17:06:19 -08001903 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001904
Lorenzo Colitti489eb042015-02-05 13:57:17 +09001905 final Network[] networks = getVpnUnderlyingNetworks(uid);
1906 if (networks != null) {
1907 // getUnderlyingNetworks() returns:
1908 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1909 // empty array => the VPN explicitly said "no default network".
1910 // non-empty array => the VPN specified one or more default networks; we use the
1911 // first one.
1912 if (networks.length > 0) {
1913 nai = getNetworkAgentInfoForNetwork(networks[0]);
1914 } else {
1915 nai = null;
Sreeram Ramachandrand2b4fe22014-11-11 16:09:21 -08001916 }
1917 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09001918 return nai;
Paul Jensen83f5d572014-08-29 09:54:01 -04001919 }
1920
1921 /**
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001922 * Check if UID should be blocked from using the specified network.
Paul Jensen83f5d572014-08-29 09:54:01 -04001923 */
paulhu7aeba372020-12-30 00:42:19 +08001924 private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
1925 final int uid, final boolean ignoreBlocked) {
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06001926 // Networks aren't blocked when ignoring blocked status
Hugo Benichi39621362017-02-11 17:04:43 +09001927 if (ignoreBlocked) {
1928 return false;
1929 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09001930 if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
paulhu7aeba372020-12-30 00:42:19 +08001931 final long ident = Binder.clearCallingIdentity();
1932 try {
1933 final boolean metered = nc == null ? true : nc.isMetered();
1934 return mPolicyManager.isUidNetworkingBlocked(uid, metered);
1935 } finally {
1936 Binder.restoreCallingIdentity(ident);
1937 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001938 }
1939
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001940 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichid159fdd2016-07-11 11:05:12 +09001941 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1942 return;
1943 }
Hugo Benichi47011212017-03-30 10:46:05 +09001944 final boolean blocked;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001945 synchronized (mBlockedAppUids) {
1946 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001947 blocked = true;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001948 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichi47011212017-03-30 10:46:05 +09001949 blocked = false;
1950 } else {
1951 return;
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001952 }
1953 }
Hugo Benichi47011212017-03-30 10:46:05 +09001954 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1955 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1956 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittiac136a02016-01-22 04:04:57 +09001957 }
1958
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001959 private void maybeLogBlockedStatusChanged(NetworkRequestInfo nri, Network net, int blocked) {
junyulaif2c67e42018-08-07 19:50:45 +08001960 if (nri == null || net == null || !LOGD_BLOCKED_NETWORKINFO) {
1961 return;
1962 }
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001963 final String action = (blocked != 0) ? "BLOCKED" : "UNBLOCKED";
James Mattisa076c532020-12-02 14:12:41 -08001964 final int requestId = nri.getActiveRequest() != null
1965 ? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
junyulai31a6c322020-05-29 14:44:42 +08001966 mNetworkInfoBlockingLogs.log(String.format(
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09001967 "%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00001968 Integer.toHexString(blocked)));
junyulaif2c67e42018-08-07 19:50:45 +08001969 }
1970
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001971 /**
Lorenzo Colittia7574052021-01-19 01:33:05 +09001972 * Apply any relevant filters to the specified {@link NetworkInfo} for the given UID. For
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06001973 * example, this may mark the network as {@link DetailedState#BLOCKED} based
paulhu7aeba372020-12-30 00:42:19 +08001974 * on {@link #isNetworkWithCapabilitiesBlocked}.
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001975 */
Lorenzo Colittia7574052021-01-19 01:33:05 +09001976 @NonNull
1977 private NetworkInfo filterNetworkInfo(@NonNull NetworkInfo networkInfo, int type,
1978 @NonNull NetworkCapabilities nc, int uid, boolean ignoreBlocked) {
Lorenzo Colitti3da6f1b2021-03-03 14:39:04 +09001979 final NetworkInfo filtered = new NetworkInfo(networkInfo);
1980 // Many legacy types (e.g,. TYPE_MOBILE_HIPRI) are not actually a property of the network
1981 // but only exists if an app asks about them or requests them. Ensure the requesting app
1982 // gets the type it asks for.
Lorenzo Colittia7574052021-01-19 01:33:05 +09001983 filtered.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09001984 if (isNetworkWithCapabilitiesBlocked(nc, uid, ignoreBlocked)) {
1985 filtered.setDetailedState(DetailedState.BLOCKED, null /* reason */,
1986 null /* extraInfo */);
1987 }
1988 filterForLegacyLockdown(filtered);
Lorenzo Colittia7574052021-01-19 01:33:05 +09001989 return filtered;
1990 }
1991
1992 private NetworkInfo getFilteredNetworkInfo(NetworkAgentInfo nai, int uid,
1993 boolean ignoreBlocked) {
1994 return filterNetworkInfo(nai.networkInfo, nai.networkInfo.getType(),
1995 nai.networkCapabilities, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07001996 }
1997
1998 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08001999 * Return NetworkInfo for the active (i.e., connected) network interface.
2000 * It is assumed that at most one network is active at a time. If more
2001 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002002 * @return the info for the active network, or {@code null} if none is
2003 * active
The Android Open Source Project28527d22009-03-03 19:31:44 -08002004 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002005 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002006 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002007 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002008 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002009 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002010 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2011 if (nai == null) return null;
2012 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2013 maybeLogBlockedNetworkInfo(networkInfo, uid);
2014 return networkInfo;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002015 }
2016
Paul Jensen1f567382015-02-13 14:18:39 -05002017 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002018 @Nullable
Paul Jensen1f567382015-02-13 14:18:39 -05002019 public Network getActiveNetwork() {
2020 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002021 return getActiveNetworkForUidInternal(mDeps.getCallingUid(), false);
Robin Lee5b52bef2016-03-24 12:07:00 +00002022 }
2023
2024 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002025 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002026 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002027 enforceNetworkStackPermission(mContext);
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002028 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Lee5b52bef2016-03-24 12:07:00 +00002029 }
2030
Chalard Jean46bfbf02022-02-02 00:56:25 +09002031 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002032 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002033 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
2034 if (vpnNai != null) {
2035 final NetworkCapabilities requiredCaps = createDefaultNetworkCapabilitiesForUid(uid);
2036 if (requiredCaps.satisfiedByNetworkCapabilities(vpnNai.networkCapabilities)) {
2037 return vpnNai.network;
Chalard Jean46adcf32018-04-18 20:18:38 +09002038 }
Paul Jensen1f567382015-02-13 14:18:39 -05002039 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002040
James Mattis2516da32021-01-31 17:06:19 -08002041 NetworkAgentInfo nai = getDefaultNetworkForUid(uid);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002042 if (nai == null || isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid,
2043 ignoreBlocked)) {
2044 return null;
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002045 }
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09002046 return nai.network;
Paul Jensen1f567382015-02-13 14:18:39 -05002047 }
2048
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002049 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002050 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002051 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
paulhu3ffffe72021-09-16 10:15:22 +08002052 enforceNetworkStackPermission(mContext);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002053 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2054 if (nai == null) return null;
2055 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002056 }
2057
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002058 /** Returns a NetworkInfo object for a network that doesn't exist. */
2059 private NetworkInfo makeFakeNetworkInfo(int networkType, int uid) {
2060 final NetworkInfo info = new NetworkInfo(networkType, 0 /* subtype */,
2061 getNetworkTypeName(networkType), "" /* subtypeName */);
2062 info.setIsAvailable(true);
2063 // For compatibility with legacy code, return BLOCKED instead of DISCONNECTED when
2064 // background data is restricted.
2065 final NetworkCapabilities nc = new NetworkCapabilities(); // Metered.
2066 final DetailedState state = isNetworkWithCapabilitiesBlocked(nc, uid, false)
2067 ? DetailedState.BLOCKED
2068 : DetailedState.DISCONNECTED;
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09002069 info.setDetailedState(state, null /* reason */, null /* extraInfo */);
2070 filterForLegacyLockdown(info);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002071 return info;
2072 }
2073
Lorenzo Colittia7574052021-01-19 01:33:05 +09002074 private NetworkInfo getFilteredNetworkInfoForType(int networkType, int uid) {
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002075 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2076 return null;
2077 }
2078 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colittia45cfb32021-03-02 23:28:49 +09002079 if (nai == null) {
2080 return makeFakeNetworkInfo(networkType, uid);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002081 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002082 return filterNetworkInfo(nai.networkInfo, networkType, nai.networkCapabilities, uid,
2083 false);
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002084 }
2085
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002086 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002087 @Nullable
The Android Open Source Project28527d22009-03-03 19:31:44 -08002088 public NetworkInfo getNetworkInfo(int networkType) {
2089 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002090 final int uid = mDeps.getCallingUid();
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002091 if (getVpnUnderlyingNetworks(uid) != null) {
2092 // A VPN is active, so we may need to return one of its underlying networks. This
2093 // information is not available in LegacyTypeTracker, so we have to get it from
Lorenzo Colittia7574052021-01-19 01:33:05 +09002094 // getNetworkAgentInfoForUid.
2095 final NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2096 if (nai == null) return null;
2097 final NetworkInfo networkInfo = getFilteredNetworkInfo(nai, uid, false);
2098 if (networkInfo.getType() == networkType) {
2099 return networkInfo;
Lorenzo Colitti489eb042015-02-05 13:57:17 +09002100 }
2101 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002102 return getFilteredNetworkInfoForType(networkType, uid);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002103 }
2104
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002105 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002106 @Nullable
Jeff Sharkey7dbf83d2016-04-28 15:33:18 -06002107 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002108 enforceAccessPermission();
Jeff Sharkey40d1fb82016-04-22 09:50:16 -06002109 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colittia7574052021-01-19 01:33:05 +09002110 if (nai == null) return null;
2111 return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002112 }
2113
2114 @Override
The Android Open Source Project28527d22009-03-03 19:31:44 -08002115 public NetworkInfo[] getAllNetworkInfo() {
2116 enforceAccessPermission();
Serik Beketayev05130302021-01-15 16:47:25 -08002117 final ArrayList<NetworkInfo> result = new ArrayList<>();
Paul Jensen42aba3e2014-09-19 11:14:12 -04002118 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
2119 networkType++) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002120 NetworkInfo info = getNetworkInfo(networkType);
2121 if (info != null) {
2122 result.add(info);
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002123 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08002124 }
Jeff Sharkey21062e72011-05-28 20:56:34 -07002125 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002126 }
2127
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002128 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002129 @Nullable
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002130 public Network getNetworkForType(int networkType) {
2131 enforceAccessPermission();
Lorenzo Colitti63aaccb2021-01-15 23:35:16 +09002132 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
2133 return null;
2134 }
2135 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2136 if (nai == null) {
2137 return null;
2138 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002139 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002140 if (isNetworkWithCapabilitiesBlocked(nai.networkCapabilities, uid, false)) {
2141 return null;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002142 }
Lorenzo Colittia7574052021-01-19 01:33:05 +09002143 return nai.network;
Lorenzo Colitti860a7aa2014-08-22 17:10:50 -07002144 }
2145
2146 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09002147 @NonNull
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002148 public Network[] getAllNetworks() {
2149 enforceAccessPermission();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002150 synchronized (mNetworkForNetId) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002151 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002152 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensenc7a1d232015-04-06 11:54:53 -04002153 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002154 }
Paul Jensenc7a1d232015-04-06 11:54:53 -04002155 return result;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002156 }
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002157 }
2158
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002159 @Override
Qingxi Lib2748102020-01-08 12:51:49 -08002160 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
Roshan Piusaa24fde2020-12-17 14:53:09 -08002161 int userId, String callingPackageName, @Nullable String callingAttributionTag) {
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002162 // The basic principle is: if an app's traffic could possibly go over a
2163 // network, without the app doing anything multinetwork-specific,
2164 // (hence, by "default"), then include that network's capabilities in
2165 // the array.
2166 //
2167 // In the normal case, app traffic only goes over the system's default
2168 // network connection, so that's the only network returned.
2169 //
2170 // With a VPN in force, some app traffic may go into the VPN, and thus
2171 // over whatever underlying networks the VPN specifies, while other app
2172 // traffic may go over the system default network (e.g.: a split-tunnel
2173 // VPN, or an app disallowed by the VPN), so the set of networks
2174 // returned includes the VPN's underlying networks and the system
2175 // default.
2176 enforceAccessPermission();
2177
Chalard Jeand6c33dc2018-06-04 13:33:12 +09002178 HashMap<Network, NetworkCapabilities> result = new HashMap<>();
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002179
James Mattis2516da32021-01-31 17:06:19 -08002180 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
2181 if (!nri.isBeingSatisfied()) {
2182 continue;
2183 }
2184 final NetworkAgentInfo nai = nri.getSatisfier();
2185 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
2186 if (null != nc
2187 && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
2188 && !result.containsKey(nai.network)) {
2189 result.put(
2190 nai.network,
2191 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002192 nc, false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002193 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
2194 callingAttributionTag));
James Mattis2516da32021-01-31 17:06:19 -08002195 }
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002196 }
2197
Lorenzo Colittidfab3032020-12-15 00:49:41 +09002198 // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09002199 final Network[] networks = getVpnUnderlyingNetworks(mDeps.getCallingUid());
James Mattis2516da32021-01-31 17:06:19 -08002200 if (null != networks) {
2201 for (final Network network : networks) {
2202 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
2203 if (null != nc) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002204 result.put(
2205 network,
2206 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002207 nc,
2208 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002209 getCallingPid(), mDeps.getCallingUid(), callingPackageName,
Roshan Piusaa24fde2020-12-17 14:53:09 -08002210 callingAttributionTag));
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09002211 }
2212 }
2213 }
2214
2215 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
2216 out = result.values().toArray(out);
2217 return out;
2218 }
2219
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002220 @Override
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002221 public boolean isNetworkSupported(int networkType) {
2222 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002223 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt0114f6e2011-08-31 11:46:42 -07002224 }
2225
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002226 /**
2227 * Return LinkProperties for the active (i.e., connected) default
James Mattis2516da32021-01-31 17:06:19 -08002228 * network interface for the calling uid.
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002229 * @return the ip properties for the active network, or {@code null} if
2230 * none is active
2231 */
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002232 @Override
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002233 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002234 enforceAccessPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002235 final int uid = mDeps.getCallingUid();
Lorenzo Colittia7574052021-01-19 01:33:05 +09002236 NetworkAgentInfo nai = getNetworkAgentInfoForUid(uid);
2237 if (nai == null) return null;
2238 return linkPropertiesRestrictedForCallerPermissions(nai.linkProperties,
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002239 Binder.getCallingPid(), uid);
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002240 }
2241
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002242 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002243 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002244 enforceAccessPermission();
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08002245 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002246 final LinkProperties lp = getLinkProperties(nai);
2247 if (lp == null) return null;
2248 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002249 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt9f0ee4f2010-09-14 09:18:02 -07002250 }
2251
Robert Greenwaltbe46b752014-05-13 21:41:06 -07002252 // TODO - this should be ALL networks
Jeff Sharkey21062e72011-05-28 20:56:34 -07002253 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002254 public LinkProperties getLinkProperties(Network network) {
2255 enforceAccessPermission();
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002256 final LinkProperties lp = getLinkProperties(getNetworkAgentInfoForNetwork(network));
2257 if (lp == null) return null;
2258 return linkPropertiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002259 lp, Binder.getCallingPid(), mDeps.getCallingUid());
Hugo Benichie9d321b2017-04-06 16:01:44 +09002260 }
2261
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002262 @Nullable
2263 private LinkProperties getLinkProperties(@Nullable NetworkAgentInfo nai) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09002264 if (nai == null) {
2265 return null;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002266 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09002267 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002268 return nai.linkProperties;
Hugo Benichie9d321b2017-04-06 16:01:44 +09002269 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002270 }
2271
lucaslinc582d502022-01-27 09:07:00 +08002272 @Override
2273 @Nullable
lucaslind2b06132022-03-02 10:56:57 +08002274 public LinkProperties getRedactedLinkPropertiesForPackage(@NonNull LinkProperties lp, int uid,
lucaslinc582d502022-01-27 09:07:00 +08002275 @NonNull String packageName, @Nullable String callingAttributionTag) {
2276 Objects.requireNonNull(packageName);
2277 Objects.requireNonNull(lp);
2278 enforceNetworkStackOrSettingsPermission();
2279 if (!checkAccessPermission(-1 /* pid */, uid)) {
2280 return null;
2281 }
2282 return linkPropertiesRestrictedForCallerPermissions(lp, -1 /* callerPid */, uid);
2283 }
2284
Qingxi Lib2748102020-01-08 12:51:49 -08002285 private NetworkCapabilities getNetworkCapabilitiesInternal(Network network) {
2286 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
2287 }
2288
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002289 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002290 if (nai == null) return null;
2291 synchronized (nai) {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002292 return networkCapabilitiesRestrictedForCallerPermissions(
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002293 nai.networkCapabilities, Binder.getCallingPid(), mDeps.getCallingUid());
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002294 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07002295 }
2296
2297 @Override
Roshan Piusaa24fde2020-12-17 14:53:09 -08002298 public NetworkCapabilities getNetworkCapabilities(Network network, String callingPackageName,
2299 @Nullable String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002300 mAppOpsManager.checkPackage(mDeps.getCallingUid(), callingPackageName);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002301 enforceAccessPermission();
Roshan Pius9ed14622020-12-28 09:01:49 -08002302 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Qingxi Lib2748102020-01-08 12:51:49 -08002303 getNetworkCapabilitiesInternal(network),
Roshan Pius951c0032020-12-22 15:10:42 -08002304 false /* includeLocationSensitiveInfo */,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002305 getCallingPid(), mDeps.getCallingUid(), callingPackageName, callingAttributionTag);
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002306 }
2307
lucaslinc582d502022-01-27 09:07:00 +08002308 @Override
lucaslind2b06132022-03-02 10:56:57 +08002309 public NetworkCapabilities getRedactedNetworkCapabilitiesForPackage(
2310 @NonNull NetworkCapabilities nc, int uid, @NonNull String packageName,
2311 @Nullable String callingAttributionTag) {
lucaslinc582d502022-01-27 09:07:00 +08002312 Objects.requireNonNull(nc);
2313 Objects.requireNonNull(packageName);
2314 enforceNetworkStackOrSettingsPermission();
2315 if (!checkAccessPermission(-1 /* pid */, uid)) {
2316 return null;
2317 }
2318 return createWithLocationInfoSanitizedIfNecessaryWhenParceled(
2319 networkCapabilitiesRestrictedForCallerPermissions(nc, -1 /* callerPid */, uid),
2320 true /* includeLocationSensitiveInfo */, -1 /* callingPid */, uid, packageName,
2321 callingAttributionTag);
2322 }
2323
lucaslin69e1aa92022-03-22 18:15:09 +08002324 private void redactUnderlyingNetworksForCapabilities(NetworkCapabilities nc, int pid, int uid) {
2325 if (nc.getUnderlyingNetworks() != null
2326 && !checkNetworkFactoryOrSettingsPermission(pid, uid)) {
2327 nc.setUnderlyingNetworks(null);
2328 }
2329 }
2330
Qingxi Libb8da982020-01-17 17:54:27 -08002331 @VisibleForTesting
2332 NetworkCapabilities networkCapabilitiesRestrictedForCallerPermissions(
Chalard Jean9a396cc2018-02-21 18:43:54 +09002333 NetworkCapabilities nc, int callerPid, int callerUid) {
lucaslinc582d502022-01-27 09:07:00 +08002334 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2335 // this would be expensive (one more permission check every time any NC callback is
2336 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2337 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2338 // send the callback) it would crash the system server with NPE.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002339 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean46adcf32018-04-18 20:18:38 +09002340 if (!checkSettingsPermission(callerPid, callerUid)) {
2341 newNc.setUids(null);
2342 newNc.setSSID(null);
2343 }
Etan Cohen107ae952018-12-30 17:59:59 -08002344 if (newNc.getNetworkSpecifier() != null) {
2345 newNc.setNetworkSpecifier(newNc.getNetworkSpecifier().redact());
2346 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002347 if (!checkAnyPermissionOf(mContext, callerPid, callerUid,
2348 android.Manifest.permission.NETWORK_STACK,
Benedict Wonga5604ea2021-07-09 00:13:45 -07002349 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)) {
2350 newNc.setAdministratorUids(new int[0]);
2351 }
Junyu Lai4c6fe232023-04-11 11:33:46 +08002352 if (!checkAnyPermissionOf(mContext,
Benedict Wong53de25f2021-03-24 14:01:51 -07002353 callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
Chalard Jeande665262022-02-25 16:12:12 +09002354 newNc.setAllowedUids(new ArraySet<>());
junyulai2217bec2021-04-14 23:33:31 +08002355 newNc.setSubscriptionIds(Collections.emptySet());
Benedict Wong53de25f2021-03-24 14:01:51 -07002356 }
lucaslin69e1aa92022-03-22 18:15:09 +08002357 redactUnderlyingNetworksForCapabilities(newNc, callerPid, callerUid);
Qingxi Libb8da982020-01-17 17:54:27 -08002358
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09002359 return newNc;
Chalard Jean2550e062018-01-26 19:24:40 +09002360 }
2361
Roshan Pius98f59ec2021-02-23 08:47:39 -08002362 /**
2363 * Wrapper used to cache the permission check results performed for the corresponding
lucaslinc582d502022-01-27 09:07:00 +08002364 * app. This avoids performing multiple permission checks for different fields in
Roshan Pius98f59ec2021-02-23 08:47:39 -08002365 * NetworkCapabilities.
2366 * Note: This wrapper does not support any sort of invalidation and thus must not be
2367 * persistent or long-lived. It may only be used for the time necessary to
2368 * compute the redactions required by one particular NetworkCallback or
2369 * synchronous call.
2370 */
2371 private class RedactionPermissionChecker {
2372 private final int mCallingPid;
2373 private final int mCallingUid;
2374 @NonNull private final String mCallingPackageName;
2375 @Nullable private final String mCallingAttributionTag;
2376
2377 private Boolean mHasLocationPermission = null;
2378 private Boolean mHasLocalMacAddressPermission = null;
2379 private Boolean mHasSettingsPermission = null;
2380
2381 RedactionPermissionChecker(int callingPid, int callingUid,
2382 @NonNull String callingPackageName, @Nullable String callingAttributionTag) {
2383 mCallingPid = callingPid;
2384 mCallingUid = callingUid;
2385 mCallingPackageName = callingPackageName;
2386 mCallingAttributionTag = callingAttributionTag;
Roshan Pius9ed14622020-12-28 09:01:49 -08002387 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002388
2389 private boolean hasLocationPermissionInternal() {
2390 final long token = Binder.clearCallingIdentity();
2391 try {
2392 return mLocationPermissionChecker.checkLocationPermission(
2393 mCallingPackageName, mCallingAttributionTag, mCallingUid,
2394 null /* message */);
2395 } finally {
2396 Binder.restoreCallingIdentity(token);
2397 }
2398 }
2399
2400 /**
2401 * Returns whether the app holds location permission or not (might return cached result
2402 * if the permission was already checked before).
2403 */
2404 public boolean hasLocationPermission() {
2405 if (mHasLocationPermission == null) {
2406 // If there is no cached result, perform the check now.
2407 mHasLocationPermission = hasLocationPermissionInternal();
2408 }
2409 return mHasLocationPermission;
2410 }
2411
2412 /**
2413 * Returns whether the app holds local mac address permission or not (might return cached
2414 * result if the permission was already checked before).
2415 */
2416 public boolean hasLocalMacAddressPermission() {
2417 if (mHasLocalMacAddressPermission == null) {
2418 // If there is no cached result, perform the check now.
2419 mHasLocalMacAddressPermission =
2420 checkLocalMacAddressPermission(mCallingPid, mCallingUid);
2421 }
2422 return mHasLocalMacAddressPermission;
2423 }
2424
2425 /**
2426 * Returns whether the app holds settings permission or not (might return cached
2427 * result if the permission was already checked before).
2428 */
2429 public boolean hasSettingsPermission() {
2430 if (mHasSettingsPermission == null) {
2431 // If there is no cached result, perform the check now.
2432 mHasSettingsPermission = checkSettingsPermission(mCallingPid, mCallingUid);
2433 }
2434 return mHasSettingsPermission;
2435 }
2436 }
2437
2438 private static boolean shouldRedact(@NetworkCapabilities.RedactionType long redactions,
2439 @NetworkCapabilities.NetCapability long redaction) {
2440 return (redactions & redaction) != 0;
2441 }
2442
2443 /**
2444 * Use the provided |applicableRedactions| to check the receiving app's
2445 * permissions and clear/set the corresponding bit in the returned bitmask. The bitmask
2446 * returned will be used to ensure the necessary redactions are performed by NetworkCapabilities
2447 * before being sent to the corresponding app.
2448 */
2449 private @NetworkCapabilities.RedactionType long retrieveRequiredRedactions(
2450 @NetworkCapabilities.RedactionType long applicableRedactions,
2451 @NonNull RedactionPermissionChecker redactionPermissionChecker,
2452 boolean includeLocationSensitiveInfo) {
2453 long redactions = applicableRedactions;
2454 if (shouldRedact(redactions, REDACT_FOR_ACCESS_FINE_LOCATION)) {
2455 if (includeLocationSensitiveInfo
2456 && redactionPermissionChecker.hasLocationPermission()) {
2457 redactions &= ~REDACT_FOR_ACCESS_FINE_LOCATION;
2458 }
2459 }
2460 if (shouldRedact(redactions, REDACT_FOR_LOCAL_MAC_ADDRESS)) {
2461 if (redactionPermissionChecker.hasLocalMacAddressPermission()) {
2462 redactions &= ~REDACT_FOR_LOCAL_MAC_ADDRESS;
2463 }
2464 }
2465 if (shouldRedact(redactions, REDACT_FOR_NETWORK_SETTINGS)) {
2466 if (redactionPermissionChecker.hasSettingsPermission()) {
2467 redactions &= ~REDACT_FOR_NETWORK_SETTINGS;
2468 }
2469 }
2470 return redactions;
Roshan Pius9ed14622020-12-28 09:01:49 -08002471 }
2472
Qingxi Lib2748102020-01-08 12:51:49 -08002473 @VisibleForTesting
2474 @Nullable
Roshan Pius9ed14622020-12-28 09:01:49 -08002475 NetworkCapabilities createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius951c0032020-12-22 15:10:42 -08002476 @Nullable NetworkCapabilities nc, boolean includeLocationSensitiveInfo,
Roshan Pius98f59ec2021-02-23 08:47:39 -08002477 int callingPid, int callingUid, @NonNull String callingPkgName,
2478 @Nullable String callingAttributionTag) {
Qingxi Lib2748102020-01-08 12:51:49 -08002479 if (nc == null) {
2480 return null;
2481 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002482 // Avoid doing location permission check if the transport info has no location sensitive
2483 // data.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002484 final RedactionPermissionChecker redactionPermissionChecker =
2485 new RedactionPermissionChecker(callingPid, callingUid, callingPkgName,
2486 callingAttributionTag);
2487 final long redactions = retrieveRequiredRedactions(
2488 nc.getApplicableRedactions(), redactionPermissionChecker,
2489 includeLocationSensitiveInfo);
2490 final NetworkCapabilities newNc = new NetworkCapabilities(nc, redactions);
Roshan Pius9ed14622020-12-28 09:01:49 -08002491 // Reset owner uid if not destined for the owner app.
lucaslinc582d502022-01-27 09:07:00 +08002492 // TODO : calling UID is redacted because apps should generally not know what UID is
2493 // bringing up the VPN, but this should not apply to some very privileged apps like settings
Roshan Pius98f59ec2021-02-23 08:47:39 -08002494 if (callingUid != nc.getOwnerUid()) {
Qingxi Lib2748102020-01-08 12:51:49 -08002495 newNc.setOwnerUid(INVALID_UID);
2496 return newNc;
2497 }
Benedict Wongbf004e92020-06-08 11:55:38 -07002498 // Allow VPNs to see ownership of their own VPN networks - not location sensitive.
2499 if (nc.hasTransport(TRANSPORT_VPN)) {
2500 // Owner UIDs already checked above. No need to re-check.
2501 return newNc;
2502 }
Roshan Pius98f59ec2021-02-23 08:47:39 -08002503 // If the calling does not want location sensitive data & target SDK >= S, then mask info.
2504 // Else include the owner UID iff the calling has location permission to provide backwards
Roshan Pius951c0032020-12-22 15:10:42 -08002505 // compatibility for older apps.
2506 if (!includeLocationSensitiveInfo
2507 && isTargetSdkAtleast(
Roshan Pius98f59ec2021-02-23 08:47:39 -08002508 Build.VERSION_CODES.S, callingUid, callingPkgName)) {
Roshan Pius951c0032020-12-22 15:10:42 -08002509 newNc.setOwnerUid(INVALID_UID);
2510 return newNc;
2511 }
Roshan Pius9ed14622020-12-28 09:01:49 -08002512 // Reset owner uid if the app has no location permission.
Roshan Pius98f59ec2021-02-23 08:47:39 -08002513 if (!redactionPermissionChecker.hasLocationPermission()) {
Roshan Pius9ed14622020-12-28 09:01:49 -08002514 newNc.setOwnerUid(INVALID_UID);
2515 }
Qingxi Lib2748102020-01-08 12:51:49 -08002516 return newNc;
Qingxi Libb8da982020-01-17 17:54:27 -08002517 }
2518
lucaslinc582d502022-01-27 09:07:00 +08002519 @NonNull
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002520 private LinkProperties linkPropertiesRestrictedForCallerPermissions(
2521 LinkProperties lp, int callerPid, int callerUid) {
2522 if (lp == null) return new LinkProperties();
lucaslinc582d502022-01-27 09:07:00 +08002523 // Note : here it would be nice to check ACCESS_NETWORK_STATE and return null, but
2524 // this would be expensive (one more permission check every time any LP callback is
2525 // sent) and possibly dangerous : apps normally can't lose ACCESS_NETWORK_STATE, if
2526 // it happens for some reason (e.g. the package is uninstalled while CS is trying to
2527 // send the callback) it would crash the system server with NPE.
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002528
2529 // Only do a permission check if sanitization is needed, to avoid unnecessary binder calls.
2530 final boolean needsSanitization =
2531 (lp.getCaptivePortalApiUrl() != null || lp.getCaptivePortalData() != null);
2532 if (!needsSanitization) {
2533 return new LinkProperties(lp);
2534 }
2535
2536 if (checkSettingsPermission(callerPid, callerUid)) {
Remi NGUYEN VAN8dd694d2020-03-16 14:48:37 +09002537 return new LinkProperties(lp, true /* parcelSensitiveFields */);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09002538 }
2539
2540 final LinkProperties newLp = new LinkProperties(lp);
2541 // Sensitive fields would not be parceled anyway, but sanitize for consistency before the
2542 // object gets parceled.
2543 newLp.setCaptivePortalApiUrl(null);
2544 newLp.setCaptivePortalData(null);
2545 return newLp;
2546 }
2547
Roshan Pius08c94fb2020-01-16 12:17:17 -08002548 private void restrictRequestUidsForCallerAndSetRequestorInfo(NetworkCapabilities nc,
2549 int callerUid, String callerPackageName) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002550 // There is no need to track the effective UID of the request here. If the caller
2551 // lacks the settings permission, the effective UID is the same as the calling ID.
Chalard Jean9a396cc2018-02-21 18:43:54 +09002552 if (!checkSettingsPermission()) {
Lorenzo Colitti86714b12021-05-17 20:31:21 +09002553 // Unprivileged apps can only pass in null or their own UID.
2554 if (nc.getUids() == null) {
2555 // If the caller passes in null, the callback will also match networks that do not
2556 // apply to its UID, similarly to what it would see if it called getAllNetworks.
2557 // In this case, redact everything in the request immediately. This ensures that the
2558 // app is not able to get any redacted information by filing an unredacted request
2559 // and observing whether the request matches something.
2560 if (nc.getNetworkSpecifier() != null) {
2561 nc.setNetworkSpecifier(nc.getNetworkSpecifier().redact());
2562 }
2563 } else {
2564 nc.setSingleUid(callerUid);
2565 }
Chalard Jean9a396cc2018-02-21 18:43:54 +09002566 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08002567 nc.setRequestorUidAndPackageName(callerUid, callerPackageName);
Cody Kesting5ab1f552020-03-16 18:15:28 -07002568 nc.setAdministratorUids(new int[0]);
Qingxi Libb8da982020-01-17 17:54:27 -08002569
2570 // Clear owner UID; this can never come from an app.
2571 nc.setOwnerUid(INVALID_UID);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002572 }
2573
Chalard Jean38354d12018-03-20 19:13:57 +09002574 private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002575 if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(mDeps.getCallingUid())) {
Chalard Jean38354d12018-03-20 19:13:57 +09002576 nc.addCapability(NET_CAPABILITY_FOREGROUND);
2577 }
2578 }
2579
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09002580 @Override
2581 public @RestrictBackgroundStatus int getRestrictBackgroundStatusByCaller() {
2582 enforceAccessPermission();
2583 final int callerUid = Binder.getCallingUid();
2584 final long token = Binder.clearCallingIdentity();
2585 try {
2586 return mPolicyManager.getRestrictBackgroundStatus(callerUid);
2587 } finally {
2588 Binder.restoreCallingIdentity(token);
2589 }
2590 }
2591
junyulaiebd15162021-03-03 12:09:05 +08002592 // TODO: Consider delete this function or turn it into a no-op method.
Lorenzo Colittie97685a2015-05-14 17:28:27 +09002593 @Override
Jeff Sharkey21062e72011-05-28 20:56:34 -07002594 public NetworkState[] getAllNetworkState() {
paulhu8e96a752019-08-12 16:25:11 +08002595 // This contains IMSI details, so make sure the caller is privileged.
paulhu3ffffe72021-09-16 10:15:22 +08002596 enforceNetworkStackPermission(mContext);
Jeff Sharkeyfffa9832014-12-02 18:30:14 -08002597
Serik Beketayev05130302021-01-15 16:47:25 -08002598 final ArrayList<NetworkState> result = new ArrayList<>();
Aaron Huangee78b1f2021-04-17 13:46:25 +08002599 for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
junyulaiebd15162021-03-03 12:09:05 +08002600 // NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
2601 // NetworkAgentInfo.
Aaron Huangb8f56642021-04-20 17:19:46 +08002602 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
junyulaid49aab92020-12-29 19:17:01 +08002603 if (nai != null && nai.networkInfo.isConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002604 result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
Aaron Huangb8f56642021-04-20 17:19:46 +08002605 snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
2606 snapshot.getNetwork(), snapshot.getSubscriberId()));
Jeff Sharkey21062e72011-05-28 20:56:34 -07002607 }
2608 }
Chalard Jean46bfbf02022-02-02 00:56:25 +09002609 return result.toArray(new NetworkState[0]);
Jeff Sharkey21062e72011-05-28 20:56:34 -07002610 }
2611
Jeff Sharkey66fa9682011-08-02 17:22:34 -07002612 @Override
junyulaiebd15162021-03-03 12:09:05 +08002613 @NonNull
Aaron Huangee78b1f2021-04-17 13:46:25 +08002614 public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
junyulaiebd15162021-03-03 12:09:05 +08002615 // This contains IMSI details, so make sure the caller is privileged.
junyulaieaaacb02021-05-14 18:04:29 +08002616 enforceNetworkStackOrSettingsPermission();
junyulaiebd15162021-03-03 12:09:05 +08002617
2618 final ArrayList<NetworkStateSnapshot> result = new ArrayList<>();
2619 for (Network network : getAllNetworks()) {
2620 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09002621 if (nai != null && nai.everConnected()) {
junyulaiebd15162021-03-03 12:09:05 +08002622 // TODO (b/73321673) : NetworkStateSnapshot contains a copy of the
2623 // NetworkCapabilities, which may contain UIDs of apps to which the
2624 // network applies. Should the UIDs be cleared so as not to leak or
2625 // interfere ?
2626 result.add(nai.getNetworkStateSnapshot());
2627 }
2628 }
2629 return result;
2630 }
2631
2632 @Override
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002633 public boolean isActiveNetworkMetered() {
2634 enforceAccessPermission();
Jeff Sharkeyd00b1302012-04-12 18:34:54 -07002635
Qingxi Lib2748102020-01-08 12:51:49 -08002636 final NetworkCapabilities caps = getNetworkCapabilitiesInternal(getActiveNetwork());
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06002637 if (caps != null) {
2638 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
2639 } else {
2640 // Always return the most conservative value
2641 return true;
2642 }
Jeff Sharkeyedf85d42012-04-30 15:47:05 -07002643 }
2644
Robert Greenwaltaffc3a12009-09-27 17:27:04 -07002645 /**
Lorenzo Colitti23862912018-09-28 11:31:55 +09002646 * Ensures that the system cannot call a particular method.
2647 */
2648 private boolean disallowedBecauseSystemCaller() {
2649 // TODO: start throwing a SecurityException when GnssLocationProvider stops calling
Anil Admale1a28862019-04-05 10:06:37 -07002650 // requestRouteToHost. In Q, GnssLocationProvider is changed to not call requestRouteToHost
2651 // for devices launched with Q and above. However, existing devices upgrading to Q and
2652 // above must continued to be supported for few more releases.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002653 if (isSystem(mDeps.getCallingUid()) && SystemProperties.getInt(
Anil Admale1a28862019-04-05 10:06:37 -07002654 "ro.product.first_api_level", 0) > Build.VERSION_CODES.P) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002655 log("This method exists only for app backwards compatibility"
2656 + " and must not be called by system services.");
2657 return true;
2658 }
2659 return false;
2660 }
2661
paulhub2c28682021-08-18 18:35:54 +08002662 private int getAppUid(final String app, final UserHandle user) {
2663 final PackageManager pm =
2664 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
2665 final long token = Binder.clearCallingIdentity();
2666 try {
2667 return pm.getPackageUid(app, 0 /* flags */);
2668 } catch (PackageManager.NameNotFoundException e) {
2669 return -1;
2670 } finally {
2671 Binder.restoreCallingIdentity(token);
2672 }
2673 }
2674
2675 private void verifyCallingUidAndPackage(String packageName, int callingUid) {
2676 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
2677 if (getAppUid(packageName, user) != callingUid) {
2678 throw new SecurityException(packageName + " does not belong to uid " + callingUid);
2679 }
2680 }
2681
Lorenzo Colitti23862912018-09-28 11:31:55 +09002682 /**
The Android Open Source Project28527d22009-03-03 19:31:44 -08002683 * Ensure that a network route exists to deliver traffic to the specified
2684 * host via the specified network interface.
Robert Greenwalt0659da32009-07-16 17:21:39 -07002685 * @param networkType the type of the network over which traffic to the
2686 * specified host is to be routed
2687 * @param hostAddress the IP address of the host to which the route is
2688 * desired
The Android Open Source Project28527d22009-03-03 19:31:44 -08002689 * @return {@code true} on success, {@code false} on failure
2690 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09002691 @Override
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002692 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress,
2693 String callingPackageName, String callingAttributionTag) {
Lorenzo Colitti23862912018-09-28 11:31:55 +09002694 if (disallowedBecauseSystemCaller()) {
2695 return false;
2696 }
paulhub2c28682021-08-18 18:35:54 +08002697 verifyCallingUidAndPackage(callingPackageName, mDeps.getCallingUid());
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002698 enforceChangePermission(callingPackageName, callingAttributionTag);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002699 if (mProtectedNetworks.contains(networkType)) {
Paul Hu8fc2a552022-05-04 18:44:42 +08002700 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002701 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002702
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002703 InetAddress addr;
2704 try {
2705 addr = InetAddress.getByAddress(hostAddress);
2706 } catch (UnknownHostException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002707 if (DBG) log("requestRouteToHostAddress got " + e);
Chad Brubaker7965e0a2014-02-14 13:24:29 -08002708 return false;
2709 }
Robert Greenwalt6cac0742011-06-21 17:26:14 -07002710
The Android Open Source Project28527d22009-03-03 19:31:44 -08002711 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002712 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project28527d22009-03-03 19:31:44 -08002713 return false;
2714 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002715
2716 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2717 if (nai == null) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09002718 if (!mLegacyTypeTracker.isTypeSupported(networkType)) {
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002719 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
2720 } else {
2721 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
2722 }
2723 return false;
Ken Mixter0c6544b2013-11-07 22:08:24 -08002724 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002725
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002726 DetailedState netState;
2727 synchronized (nai) {
2728 netState = nai.networkInfo.getDetailedState();
2729 }
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002730
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002731 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt78f28112011-08-02 17:18:41 -07002732 if (VDBG) {
Wink Saville32506bc2013-06-29 21:10:57 -07002733 log("requestRouteToHostAddress on down network "
2734 + "(" + networkType + ") - dropped"
Robert Greenwaltae5370c2014-06-03 17:22:11 -07002735 + " netState=" + netState);
Robert Greenwalt4666ed02009-09-10 15:06:20 -07002736 }
2737 return false;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002738 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002739
Lorenzo Colittif61ca942020-12-15 11:02:22 +09002740 final int uid = mDeps.getCallingUid();
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002741 final long token = Binder.clearCallingIdentity();
Robert Greenwalta7dfbd32010-06-15 15:43:39 -07002742 try {
Paul Jensen65743a22014-07-11 08:17:29 -04002743 LinkProperties lp;
2744 int netId;
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002745 synchronized (nai) {
2746 lp = nai.linkProperties;
Serik Beketayevec8ad212020-12-07 22:43:07 -08002747 netId = nai.network.getNetId();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07002748 }
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002749 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Lorenzo Colittia2e1fe82021-04-10 01:01:43 +09002750 if (DBG) {
2751 log("requestRouteToHostAddress " + addr + nai.toShortString() + " ok=" + ok);
2752 }
Wink Saville32506bc2013-06-29 21:10:57 -07002753 return ok;
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002754 } finally {
2755 Binder.restoreCallingIdentity(token);
2756 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07002757 }
2758
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002759 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002760 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwalt98107422011-07-22 11:55:33 -07002761 if (bestRoute == null) {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002762 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwalt98107422011-07-22 11:55:33 -07002763 } else {
Lorenzo Colittie43b6c42013-03-15 13:58:38 +09002764 String iface = bestRoute.getInterface();
Robert Greenwalt98107422011-07-22 11:55:33 -07002765 if (bestRoute.getGateway().equals(addr)) {
2766 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002767 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002768 } else {
2769 // if we will connect to this through another route, add a direct route
2770 // to it's gateway
Lorenzo Colitti7a43b0f2013-03-08 12:30:44 -08002771 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwalt98107422011-07-22 11:55:33 -07002772 }
2773 }
Lorenzo Colitti4e69f082015-09-04 13:12:42 +09002774 if (DBG) log("Adding legacy route " + bestRoute +
2775 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Chiachang Wang6f952792020-11-06 14:48:30 +08002776
2777 final String dst = bestRoute.getDestinationLinkAddress().toString();
2778 final String nextHop = bestRoute.hasGateway()
2779 ? bestRoute.getGateway().getHostAddress() : "";
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002780 try {
Chiachang Wang6f952792020-11-06 14:48:30 +08002781 mNetd.networkAddLegacyRoute(netId, bestRoute.getInterface(), dst, nextHop , uid);
2782 } catch (RemoteException | ServiceSpecificException e) {
Sreeram Ramachandranc06ec732014-07-19 23:21:46 -07002783 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt7fa3bdb2011-12-13 15:26:02 -08002784 return false;
2785 }
Robert Greenwalte8d2a4a2011-07-14 14:28:05 -07002786 return true;
The Android Open Source Project28527d22009-03-03 19:31:44 -08002787 }
2788
paulhu7c0a2e62021-01-08 00:51:49 +08002789 class DnsResolverUnsolicitedEventCallback extends
2790 IDnsResolverUnsolicitedEventListener.Stub {
dalyk1720e542018-03-05 12:42:22 -05002791 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002792 public void onPrivateDnsValidationEvent(final PrivateDnsValidationEventParcel event) {
dalyk1720e542018-03-05 12:42:22 -05002793 try {
2794 mHandler.sendMessage(mHandler.obtainMessage(
2795 EVENT_PRIVATE_DNS_VALIDATION_UPDATE,
paulhu7c0a2e62021-01-08 00:51:49 +08002796 new PrivateDnsValidationUpdate(event.netId,
2797 InetAddresses.parseNumericAddress(event.ipAddress),
2798 event.hostname, event.validation)));
dalyk1720e542018-03-05 12:42:22 -05002799 } catch (IllegalArgumentException e) {
2800 loge("Error parsing ip address in validation event");
2801 }
2802 }
Chiachang Wang686e7c02018-11-27 18:00:05 +08002803
2804 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002805 public void onDnsHealthEvent(final DnsHealthEventParcel event) {
2806 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(event.netId);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002807 // Netd event only allow registrants from system. Each NetworkMonitor thread is under
2808 // the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
2809 // event callback for certain nai. e.g. cellular. Register here to pass to
2810 // NetworkMonitor instead.
Chalard Jean46bfbf02022-02-02 00:56:25 +09002811 // TODO: Move the Dns Event to NetworkMonitor. NetdEventListenerService only allows one
Remi NGUYEN VAN6bf8f0f2019-02-04 10:25:11 +09002812 // callback from each caller type. Need to re-factor NetdEventListenerService to allow
2813 // multiple NetworkMonitor registrants.
Chalard Jean5b409c72021-02-04 13:12:59 +09002814 if (nai != null && nai.satisfies(mDefaultRequest.mRequests.get(0))) {
paulhu7c0a2e62021-01-08 00:51:49 +08002815 nai.networkMonitor().notifyDnsResponse(event.healthResult);
Chiachang Wang686e7c02018-11-27 18:00:05 +08002816 }
2817 }
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002818
2819 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002820 public void onNat64PrefixEvent(final Nat64PrefixEventParcel event) {
2821 mHandler.post(() -> handleNat64PrefixEvent(event.netId, event.prefixOperation,
2822 event.prefixAddress, event.prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09002823 }
dalyk1720e542018-03-05 12:42:22 -05002824
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002825 @Override
paulhu7c0a2e62021-01-08 00:51:49 +08002826 public int getInterfaceVersion() {
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002827 return this.VERSION;
2828 }
2829
2830 @Override
2831 public String getInterfaceHash() {
2832 return this.HASH;
2833 }
paulhu7c0a2e62021-01-08 00:51:49 +08002834 }
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002835
2836 @VisibleForTesting
paulhu7c0a2e62021-01-08 00:51:49 +08002837 protected final DnsResolverUnsolicitedEventCallback mResolverUnsolEventCallback =
2838 new DnsResolverUnsolicitedEventCallback();
Lorenzo Colitti5cefdf22021-01-07 17:16:24 +09002839
paulhu7c0a2e62021-01-08 00:51:49 +08002840 private void registerDnsResolverUnsolicitedEventListener() {
dalyk1720e542018-03-05 12:42:22 -05002841 try {
paulhu7c0a2e62021-01-08 00:51:49 +08002842 mDnsResolver.registerUnsolicitedEventListener(mResolverUnsolEventCallback);
dalyk1720e542018-03-05 12:42:22 -05002843 } catch (Exception e) {
paulhu7c0a2e62021-01-08 00:51:49 +08002844 loge("Error registering DnsResolver unsolicited event callback: " + e);
dalyk1720e542018-03-05 12:42:22 -05002845 }
2846 }
2847
Sudheer Shanka9967d462021-03-18 19:09:25 +00002848 private final NetworkPolicyCallback mPolicyCallback = new NetworkPolicyCallback() {
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002849 @Override
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002850 public void onUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002851 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UID_BLOCKED_REASON_CHANGED,
2852 uid, blockedReasons));
Jeff Sharkeyb1b6ccd2012-02-07 12:05:43 -08002853 }
Jeff Sharkey921ebf22011-05-19 17:12:49 -07002854 };
2855
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002856 private void handleUidBlockedReasonChanged(int uid, @BlockedReason int blockedReasons) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00002857 maybeNotifyNetworkBlockedForNewState(uid, blockedReasons);
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09002858 setUidBlockedReasons(uid, blockedReasons);
junyulaif2c67e42018-08-07 19:50:45 +08002859 }
2860
Paul Jensen83f5d572014-08-29 09:54:01 -04002861 private void enforceInternetPermission() {
2862 mContext.enforceCallingOrSelfPermission(
2863 android.Manifest.permission.INTERNET,
2864 "ConnectivityService");
2865 }
2866
The Android Open Source Project28527d22009-03-03 19:31:44 -08002867 private void enforceAccessPermission() {
Robert Greenwalt0659da32009-07-16 17:21:39 -07002868 mContext.enforceCallingOrSelfPermission(
2869 android.Manifest.permission.ACCESS_NETWORK_STATE,
2870 "ConnectivityService");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002871 }
2872
lucaslinc582d502022-01-27 09:07:00 +08002873 private boolean checkAccessPermission(int pid, int uid) {
2874 return mContext.checkPermission(android.Manifest.permission.ACCESS_NETWORK_STATE, pid, uid)
2875 == PERMISSION_GRANTED;
2876 }
2877
paulhua6ee2122021-02-22 15:40:43 +08002878 /**
2879 * Performs a strict and comprehensive check of whether a calling package is allowed to
2880 * change the state of network, as the condition differs for pre-M, M+, and
2881 * privileged/preinstalled apps. The caller is expected to have either the
2882 * CHANGE_NETWORK_STATE or the WRITE_SETTINGS permission declared. Either of these
2883 * permissions allow changing network state; WRITE_SETTINGS is a runtime permission and
2884 * can be revoked, but (except in M, excluding M MRs), CHANGE_NETWORK_STATE is a normal
2885 * permission and cannot be revoked. See http://b/23597341
2886 *
2887 * Note: if the check succeeds because the application holds WRITE_SETTINGS, the operation
2888 * of this app will be updated to the current time.
2889 */
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07002890 private void enforceChangePermission(String callingPkg, String callingAttributionTag) {
paulhua6ee2122021-02-22 15:40:43 +08002891 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.CHANGE_NETWORK_STATE)
2892 == PackageManager.PERMISSION_GRANTED) {
2893 return;
2894 }
2895
2896 if (callingPkg == null) {
2897 throw new SecurityException("Calling package name is null.");
2898 }
2899
2900 final AppOpsManager appOpsMgr = mContext.getSystemService(AppOpsManager.class);
2901 final int uid = mDeps.getCallingUid();
2902 final int mode = appOpsMgr.noteOpNoThrow(AppOpsManager.OPSTR_WRITE_SETTINGS, uid,
2903 callingPkg, callingAttributionTag, null /* message */);
2904
2905 if (mode == AppOpsManager.MODE_ALLOWED) {
2906 return;
2907 }
2908
2909 if ((mode == AppOpsManager.MODE_DEFAULT) && (mContext.checkCallingOrSelfPermission(
2910 android.Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED)) {
2911 return;
2912 }
2913
2914 throw new SecurityException(callingPkg + " was not granted either of these permissions:"
2915 + android.Manifest.permission.CHANGE_NETWORK_STATE + ","
2916 + android.Manifest.permission.WRITE_SETTINGS + ".");
The Android Open Source Project28527d22009-03-03 19:31:44 -08002917 }
2918
Charles He9369e612017-05-15 17:07:18 +01002919 private void enforceSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002920 enforceAnyPermissionOf(mContext,
Charles He9369e612017-05-15 17:07:18 +01002921 android.Manifest.permission.NETWORK_SETTINGS,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002922 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Charles He9369e612017-05-15 17:07:18 +01002923 }
2924
Quang Luong98858d62023-02-11 00:25:24 +00002925 private void enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission() {
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08002926 enforceAnyPermissionOf(mContext,
2927 android.Manifest.permission.NETWORK_SETTINGS,
Quang Luong98858d62023-02-11 00:25:24 +00002928 android.Manifest.permission.NETWORK_SETUP_WIZARD,
Junyu Laiaa4ad8c2022-10-28 15:42:00 +08002929 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
2930 Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS);
2931 }
2932
paulhu8e96a752019-08-12 16:25:11 +08002933 private void enforceNetworkFactoryPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002934 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002935 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002936 enforceAnyPermissionOf(mContext,
paulhu8e96a752019-08-12 16:25:11 +08002937 android.Manifest.permission.NETWORK_FACTORY,
paulhub6ba8e82020-03-04 09:43:41 +08002938 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
paulhu8e96a752019-08-12 16:25:11 +08002939 }
2940
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002941 private void enforceNetworkFactoryOrSettingsPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002942 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002943 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002944 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002945 android.Manifest.permission.NETWORK_SETTINGS,
2946 android.Manifest.permission.NETWORK_FACTORY,
2947 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2948 }
2949
2950 private void enforceNetworkFactoryOrTestNetworksPermission() {
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002951 // TODO: Check for the BLUETOOTH_STACK permission once that is in the API surface.
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002952 if (UserHandle.getAppId(getCallingUid()) == Process.BLUETOOTH_UID) return;
paulhu3ffffe72021-09-16 10:15:22 +08002953 enforceAnyPermissionOf(mContext,
Aaron Huangebbfd3c2020-04-14 13:43:49 +08002954 android.Manifest.permission.MANAGE_TEST_NETWORKS,
2955 android.Manifest.permission.NETWORK_FACTORY,
2956 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
2957 }
2958
lucaslin69e1aa92022-03-22 18:15:09 +08002959 private boolean checkNetworkFactoryOrSettingsPermission(int pid, int uid) {
2960 return PERMISSION_GRANTED == mContext.checkPermission(
2961 android.Manifest.permission.NETWORK_FACTORY, pid, uid)
2962 || PERMISSION_GRANTED == mContext.checkPermission(
2963 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2964 || PERMISSION_GRANTED == mContext.checkPermission(
Lorenzo Colittid12af7e2022-04-06 09:56:22 +09002965 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid)
Andrew Cheng2ae5c732022-04-18 17:21:57 -07002966 || UserHandle.getAppId(uid) == Process.BLUETOOTH_UID;
lucaslin69e1aa92022-03-22 18:15:09 +08002967 }
2968
Chalard Jean9a396cc2018-02-21 18:43:54 +09002969 private boolean checkSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002970 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002971 android.Manifest.permission.NETWORK_SETTINGS,
2972 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002973 }
2974
2975 private boolean checkSettingsPermission(int pid, int uid) {
2976 return PERMISSION_GRANTED == mContext.checkPermission(
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002977 android.Manifest.permission.NETWORK_SETTINGS, pid, uid)
2978 || PERMISSION_GRANTED == mContext.checkPermission(
2979 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, pid, uid);
Chalard Jean9a396cc2018-02-21 18:43:54 +09002980 }
2981
paulhu8e96a752019-08-12 16:25:11 +08002982 private void enforceNetworkStackOrSettingsPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002983 enforceNetworkStackPermissionOr(mContext,
2984 android.Manifest.permission.NETWORK_SETTINGS);
paulhu8e96a752019-08-12 16:25:11 +08002985 }
2986
Lorenzo Colittic7da00d2018-10-09 18:55:11 +09002987 private void enforceNetworkStackSettingsOrSetup() {
paulhu3ffffe72021-09-16 10:15:22 +08002988 enforceNetworkStackPermissionOr(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09002989 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002990 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00002991 }
2992
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002993 private void enforceAirplaneModePermission() {
paulhu3ffffe72021-09-16 10:15:22 +08002994 enforceNetworkStackPermissionOr(mContext,
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002995 android.Manifest.permission.NETWORK_AIRPLANE_MODE,
2996 android.Manifest.permission.NETWORK_SETTINGS,
paulhu3ffffe72021-09-16 10:15:22 +08002997 android.Manifest.permission.NETWORK_SETUP_WIZARD);
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01002998 }
2999
James Mattis8378aec2021-01-26 14:05:36 -08003000 private void enforceOemNetworkPreferencesPermission() {
3001 mContext.enforceCallingOrSelfPermission(
3002 android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE,
3003 "ConnectivityService");
3004 }
3005
James Mattisfa270db2021-05-31 17:11:10 -07003006 private void enforceManageTestNetworksPermission() {
3007 mContext.enforceCallingOrSelfPermission(
3008 android.Manifest.permission.MANAGE_TEST_NETWORKS,
3009 "ConnectivityService");
3010 }
3011
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003012 private boolean checkNetworkStackPermission() {
paulhu3ffffe72021-09-16 10:15:22 +08003013 return PermissionUtils.checkAnyPermissionOf(mContext,
Remi NGUYEN VAN097a5972019-01-31 16:42:12 +09003014 android.Manifest.permission.NETWORK_STACK,
3015 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -07003016 }
3017
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003018 private boolean checkNetworkStackPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003019 return checkAnyPermissionOf(mContext, pid, uid,
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003020 android.Manifest.permission.NETWORK_STACK,
3021 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK);
3022 }
3023
paulhu1a407652019-03-22 16:35:06 +08003024 private boolean checkNetworkSignalStrengthWakeupPermission(int pid, int uid) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08003025 return checkAnyPermissionOf(mContext, pid, uid,
paulhu1a407652019-03-22 16:35:06 +08003026 android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP,
Chalard Jean6b59b8f2020-04-13 21:54:58 +09003027 NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
3028 android.Manifest.permission.NETWORK_SETTINGS);
paulhu1a407652019-03-22 16:35:06 +08003029 }
3030
Paul Hu8fc2a552022-05-04 18:44:42 +08003031 private boolean checkConnectivityRestrictedNetworksPermission(int callingUid,
3032 boolean checkUidsAllowedList) {
3033 if (PermissionUtils.checkAnyPermissionOf(mContext,
3034 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS)) {
3035 return true;
3036 }
3037
3038 // fallback to ConnectivityInternalPermission
3039 // TODO: Remove this fallback check after all apps have declared
3040 // CONNECTIVITY_USE_RESTRICTED_NETWORKS.
3041 if (PermissionUtils.checkAnyPermissionOf(mContext,
3042 android.Manifest.permission.CONNECTIVITY_INTERNAL)) {
3043 return true;
3044 }
3045
3046 // Check whether uid is in allowed on restricted networks list.
3047 if (checkUidsAllowedList
3048 && mPermissionMonitor.isUidAllowedOnRestrictedNetworks(callingUid)) {
3049 return true;
3050 }
3051 return false;
3052 }
3053
3054 private void enforceConnectivityRestrictedNetworksPermission(boolean checkUidsAllowedList) {
3055 final int callingUid = mDeps.getCallingUid();
3056 if (!checkConnectivityRestrictedNetworksPermission(callingUid, checkUidsAllowedList)) {
3057 throw new SecurityException("ConnectivityService: user " + callingUid
3058 + " has no permission to access restricted network.");
3059 }
Hugo Benichibd0cc762016-07-19 15:59:27 +09003060 }
3061
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003062 private void enforceKeepalivePermission() {
chiachangwang9ef4ffe2023-01-18 01:19:27 +00003063 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003064 }
3065
Roshan Pius98f59ec2021-02-23 08:47:39 -08003066 private boolean checkLocalMacAddressPermission(int pid, int uid) {
3067 return PERMISSION_GRANTED == mContext.checkPermission(
3068 Manifest.permission.LOCAL_MAC_ADDRESS, pid, uid);
3069 }
3070
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09003071 private void sendConnectedBroadcast(NetworkInfo info) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003072 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003073 }
3074
3075 private void sendInetConditionBroadcast(NetworkInfo info) {
3076 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
3077 }
3078
Wink Saville4f0de1e2011-08-04 15:01:58 -07003079 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Robert Greenwaltd3401f92010-09-15 17:36:33 -07003080 Intent intent = new Intent(bcastType);
Irfan Sheriff32bed2c2012-09-20 09:32:41 -07003081 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey47905d12012-08-06 11:41:50 -07003082 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003083 if (info.isFailover()) {
3084 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
3085 info.setFailover(false);
3086 }
3087 if (info.getReason() != null) {
3088 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
3089 }
3090 if (info.getExtraInfo() != null) {
Robert Greenwalt0659da32009-07-16 17:21:39 -07003091 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
3092 info.getExtraInfo());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003093 }
Robert Greenwalt986c7412010-09-08 15:24:47 -07003094 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville4f0de1e2011-08-04 15:01:58 -07003095 return intent;
3096 }
3097
3098 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
3099 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
3100 }
3101
Michael Groover73f69482023-01-27 11:01:25 -06003102 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
3103 @SuppressLint("NewApi")
Chiachang Wang3bc52762021-11-25 14:17:57 +08003104 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
3105 @TargetApi(Build.VERSION_CODES.S)
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003106 private void sendStickyBroadcast(Intent intent) {
Hugo Benichie5220992017-04-26 14:53:28 +09003107 synchronized (this) {
Chalard Jean09335372018-06-08 14:24:49 +09003108 if (!mSystemReady
3109 && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Dianne Hackborna417ff82009-12-08 19:45:14 -08003110 mInitialBroadcast = new Intent(intent);
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003111 }
Dianne Hackborna417ff82009-12-08 19:45:14 -08003112 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09003113 if (VDBG) {
Jeff Sharkey971cd162011-08-29 16:02:57 -07003114 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville4f0de1e2011-08-04 15:01:58 -07003115 }
3116
Dianne Hackborn66dd0332015-12-09 17:22:26 -08003117 Bundle options = null;
Dianne Hackborne588ca12012-09-04 18:48:37 -07003118 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003119 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalt6803efe2015-09-01 08:23:04 -07003120 final NetworkInfo ni = intent.getParcelableExtra(
3121 ConnectivityManager.EXTRA_NETWORK_INFO);
paulhu27ca4492020-02-03 19:52:43 +08003122 final BroadcastOptions opts = BroadcastOptions.makeBasic();
3123 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003124 applyMostRecentPolicyForConnectivityAction(opts, ni);
paulhu27ca4492020-02-03 19:52:43 +08003125 options = opts.toBundle();
Chad Brubakercaced412018-03-08 10:37:09 -08003126 intent.addFlags(Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackborn37e2d0e2014-12-04 17:46:42 -08003127 }
Dianne Hackborne588ca12012-09-04 18:48:37 -07003128 try {
Paul Hu96f1cbb2021-01-26 02:53:06 +00003129 mUserAllContext.sendStickyBroadcast(intent, options);
Dianne Hackborne588ca12012-09-04 18:48:37 -07003130 } finally {
3131 Binder.restoreCallingIdentity(ident);
3132 }
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003133 }
3134 }
3135
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003136 private void applyMostRecentPolicyForConnectivityAction(BroadcastOptions options,
3137 NetworkInfo info) {
3138 // Delivery group policy APIs are only available on U+.
3139 if (!SdkLevel.isAtLeastU()) return;
3140
3141 final BroadcastOptionsShim optsShim = mDeps.makeBroadcastOptionsShim(options);
3142 try {
3143 // This allows us to discard older broadcasts still waiting to be delivered
3144 // which have the same namespace and key.
3145 optsShim.setDeliveryGroupPolicy(ConstantsShim.DELIVERY_GROUP_POLICY_MOST_RECENT);
3146 optsShim.setDeliveryGroupMatchingKey(ConnectivityManager.CONNECTIVITY_ACTION,
3147 createDeliveryGroupKeyForConnectivityAction(info));
Jeff Sharkey4ffd34c2023-03-06 14:10:30 -07003148 optsShim.setDeferralPolicy(ConstantsShim.DEFERRAL_POLICY_UNTIL_ACTIVE);
Sudheer Shanka2453a3a2022-11-29 15:15:50 -08003149 } catch (UnsupportedApiLevelException e) {
3150 Log.wtf(TAG, "Using unsupported API" + e);
3151 }
3152 }
3153
3154 @VisibleForTesting
3155 static String createDeliveryGroupKeyForConnectivityAction(NetworkInfo info) {
3156 final StringBuilder sb = new StringBuilder();
3157 sb.append(info.getType()).append(DELIVERY_GROUP_KEY_DELIMITER);
3158 sb.append(info.getSubtype()).append(DELIVERY_GROUP_KEY_DELIMITER);
3159 sb.append(info.getExtraInfo());
3160 return sb.toString();
3161 }
3162
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003163 /**
Aaron Huang96011892020-06-27 07:18:23 +08003164 * Called by SystemServer through ConnectivityManager when the system is ready.
3165 */
3166 @Override
3167 public void systemReady() {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003168 if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
Aaron Huang96011892020-06-27 07:18:23 +08003169 throw new SecurityException("Calling Uid is not system uid.");
3170 }
3171 systemReadyInternal();
3172 }
3173
3174 /**
3175 * Called when ConnectivityService can initialize remaining components.
Remi NGUYEN VAN317b2d22019-06-20 18:29:36 +09003176 */
3177 @VisibleForTesting
Aaron Huang96011892020-06-27 07:18:23 +08003178 public void systemReadyInternal() {
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09003179 // Load flags after PackageManager is ready to query module version
3180 mFlags.loadFlags(mDeps, mContext);
3181
Aaron Huang9a57acf2020-12-08 10:03:29 +08003182 // Since mApps in PermissionMonitor needs to be populated first to ensure that
3183 // listening network request which is sent by MultipathPolicyTracker won't be added
3184 // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
3185 // be called after PermissionMonitor#startMonitoring().
3186 // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
3187 // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
3188 // to ensure the tracking will be initialized correctly.
Paul Hu3c8c8102022-08-25 07:06:16 +00003189 final ConditionVariable startMonitoringDone = new ConditionVariable();
3190 mHandler.post(() -> {
3191 mPermissionMonitor.startMonitoring();
3192 startMonitoringDone.open();
3193 });
Chalard Jeane4f9bd92018-06-08 12:47:42 +09003194 mProxyTracker.loadGlobalProxy();
paulhu7c0a2e62021-01-08 00:51:49 +08003195 registerDnsResolverUnsolicitedEventListener();
Wink Saville9a1a7ef2013-08-29 08:55:16 -07003196
Hugo Benichie5220992017-04-26 14:53:28 +09003197 synchronized (this) {
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003198 mSystemReady = true;
Dianne Hackborna417ff82009-12-08 19:45:14 -08003199 if (mInitialBroadcast != null) {
Dianne Hackborn22986892012-08-29 18:32:08 -07003200 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborna417ff82009-12-08 19:45:14 -08003201 mInitialBroadcast = null;
Mike Lockwoodfde2b762009-08-14 14:18:49 -04003202 }
3203 }
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07003204
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07003205 // Create network requests for always-on networks.
3206 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
paulhu51f77dc2021-06-07 02:34:20 +00003207
3208 // Update mobile data preference if necessary.
Chalard Jean46bfbf02022-02-02 00:56:25 +09003209 // Note that updating can be skipped here if the list is empty only because no uid
3210 // rules are applied before system ready. Normally, the empty uid list means to clear
3211 // the uids rules on netd.
paulhu51f77dc2021-06-07 02:34:20 +00003212 if (!ConnectivitySettingsManager.getMobileDataPreferredUids(mContext).isEmpty()) {
3213 updateMobileDataPreferredUids();
3214 }
Motomu Utsumi166f9662022-09-01 10:35:29 +09003215
3216 // On T+ devices, register callback for statsd to pull NETWORK_BPF_MAP_INFO atom
3217 if (SdkLevel.isAtLeastT()) {
3218 mBpfNetMaps.setPullAtomCallback(mContext);
3219 }
Paul Hu3c8c8102022-08-25 07:06:16 +00003220 // Wait PermissionMonitor to finish the permission update. Then MultipathPolicyTracker won't
3221 // have permission problem. While CV#block() is unbounded in time and can in principle block
3222 // forever, this replaces a synchronous call to PermissionMonitor#startMonitoring, which
3223 // could have blocked forever too.
3224 startMonitoringDone.block();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003225 }
3226
The Android Open Source Project28527d22009-03-03 19:31:44 -08003227 /**
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003228 * Start listening for default data network activity state changes.
3229 */
3230 @Override
3231 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003232 mNetworkActivityTracker.registerNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003233 }
3234
3235 /**
3236 * Stop listening for default data network activity state changes.
3237 */
3238 @Override
3239 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
lucaslin1193a5d2021-01-21 02:04:15 +08003240 mNetworkActivityTracker.unregisterNetworkActivityListener(l);
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003241 }
3242
3243 /**
3244 * Check whether the default network radio is currently active.
3245 */
3246 @Override
3247 public boolean isDefaultNetworkActive() {
lucaslin1193a5d2021-01-21 02:04:15 +08003248 return mNetworkActivityTracker.isDefaultNetworkActive();
Chiachang Wang4068dcb2020-12-15 15:56:00 +08003249 }
3250
3251 /**
Chalard Jean9dd11612018-06-04 16:52:49 +09003252 * Reads the network specific MTU size from resources.
sy.yun4aa73922013-09-02 05:24:09 +09003253 * and set it on it's iface.
3254 */
Junyu Lai970963e2022-10-25 15:46:47 +08003255 private void updateMtu(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003256 final String iface = newLp.getInterfaceName();
3257 final int mtu = newLp.getMtu();
Hansen Kurli04252032022-12-07 11:21:49 +00003258 if (mtu == 0) {
Pierre Imai07c53a32016-02-08 16:01:40 +09003259 // Silently ignore unset MTU value.
3260 return;
3261 }
Hansen Kurli04252032022-12-07 11:21:49 +00003262 if (oldLp != null && newLp.isIdenticalMtu(oldLp)
3263 && TextUtils.equals(oldLp.getInterfaceName(), iface)) {
3264 if (VDBG) log("identical MTU and iface - not setting");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003265 return;
3266 }
Hansen Kurli04252032022-12-07 11:21:49 +00003267 // Cannot set MTU without interface name
3268 if (TextUtils.isEmpty(iface)) {
3269 if (VDBG) log("Setting MTU size with null iface.");
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003270 return;
3271 }
sy.yun4aa73922013-09-02 05:24:09 +09003272
Hansen Kurli04252032022-12-07 11:21:49 +00003273 if (!LinkProperties.isValidMtu(mtu, newLp.hasGlobalIpv6Address())) {
3274 loge("Unexpected mtu value: " + mtu + ", " + iface);
w19976e714f1d2014-08-05 15:18:11 -07003275 return;
3276 }
3277
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003278 try {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09003279 if (VDBG || DDBG) log("Setting MTU size: " + iface + ", " + mtu);
Chiachang Wang6d5c0e72020-10-26 17:13:09 +08003280 mNetd.interfaceSetMtu(iface, mtu);
3281 } catch (RemoteException | ServiceSpecificException e) {
Aaron Huang6616df32020-10-30 22:04:25 +08003282 loge("exception in interfaceSetMtu()" + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003283 }
3284 }
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003285
Chenbo Feng15416292018-11-08 17:36:21 -08003286 @VisibleForTesting
3287 protected static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensenbb910e92015-05-13 14:05:12 -04003288
Junyu Lai970963e2022-10-25 15:46:47 +08003289 private void updateTcpBufferSizes(@Nullable String tcpBufferSizes) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003290 String[] values = null;
3291 if (tcpBufferSizes != null) {
3292 values = tcpBufferSizes.split(",");
3293 }
3294
3295 if (values == null || values.length != 6) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07003296 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003297 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
3298 values = tcpBufferSizes.split(",");
3299 }
3300
3301 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
3302
3303 try {
Aaron Huang6616df32020-10-30 22:04:25 +08003304 if (VDBG || DDBG) log("Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003305
Chenbo Feng15416292018-11-08 17:36:21 -08003306 String rmemValues = String.join(" ", values[0], values[1], values[2]);
3307 String wmemValues = String.join(" ", values[3], values[4], values[5]);
3308 mNetd.setTcpRWmemorySize(rmemValues, wmemValues);
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003309 mCurrentTcpBufferSizes = tcpBufferSizes;
Chenbo Feng15416292018-11-08 17:36:21 -08003310 } catch (RemoteException | ServiceSpecificException e) {
Robert Greenwaltdebf0e02014-08-06 12:00:25 -07003311 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriff7f132d92010-06-09 15:39:36 -07003312 }
3313 }
3314
Robert Greenwalt3dc73e52014-05-15 18:07:26 -07003315 @Override
3316 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitticd447b22017-03-21 18:54:11 +09003317 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt2034b912009-08-12 16:08:25 -07003318 NETWORK_RESTORE_DELAY_PROP_NAME);
3319 if(restoreDefaultNetworkDelayStr != null &&
3320 restoreDefaultNetworkDelayStr.length() != 0) {
3321 try {
Narayan Kamath46f0dd62016-04-15 18:32:45 +01003322 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt2034b912009-08-12 16:08:25 -07003323 } catch (NumberFormatException e) {
3324 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08003325 }
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003326 // if the system property isn't set, use the value for the apn type
3327 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
3328
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09003329 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
3330 ret = mLegacyTypeTracker.getRestoreTimerForType(networkType);
Robert Greenwalt20f819c2011-05-03 19:02:44 -07003331 }
3332 return ret;
The Android Open Source Project28527d22009-03-03 19:31:44 -08003333 }
3334
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003335 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
Chalard Jean46bfbf02022-02-02 00:56:25 +09003336 final List<NetworkDiagnostics> netDiags = new ArrayList<>();
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003337 final long DIAG_TIME_MS = 5000;
Hugo Benichia480ba52018-09-03 08:19:02 +09003338 for (NetworkAgentInfo nai : networksSortedById()) {
Mike Yu6cad4b12019-07-05 11:51:34 +08003339 PrivateDnsConfig privateDnsCfg = mDnsManager.getPrivateDnsConfig(nai.network);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003340 // Start gathering diagnostic information.
3341 netDiags.add(new NetworkDiagnostics(
3342 nai.network,
3343 new LinkProperties(nai.linkProperties), // Must be a copy.
Mike Yu6cad4b12019-07-05 11:51:34 +08003344 privateDnsCfg,
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003345 DIAG_TIME_MS));
3346 }
3347
3348 for (NetworkDiagnostics netDiag : netDiags) {
3349 pw.println();
3350 netDiag.waitForMeasurements();
3351 netDiag.dump(pw);
3352 }
3353 }
3354
The Android Open Source Project28527d22009-03-03 19:31:44 -08003355 @Override
Chalard Jeanfbab6d42019-09-26 18:03:47 +09003356 protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
3357 @Nullable String[] args) {
Chiachang Wanga101f852021-04-19 10:59:24 +08003358 if (!checkDumpPermission(mContext, TAG, writer)) return;
3359
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003360 mPriorityDumper.dump(fd, writer, args);
Vishnu Nair0701e422017-10-26 10:08:50 -07003361 }
3362
lucaslin99473f62020-12-10 15:10:54 +08003363 private boolean checkDumpPermission(Context context, String tag, PrintWriter pw) {
3364 if (context.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
3365 != PackageManager.PERMISSION_GRANTED) {
3366 pw.println("Permission Denial: can't dump " + tag + " from from pid="
Lorenzo Colittif61ca942020-12-15 11:02:22 +09003367 + Binder.getCallingPid() + ", uid=" + mDeps.getCallingUid()
lucaslin99473f62020-12-10 15:10:54 +08003368 + " due to missing android.permission.DUMP permission");
3369 return false;
3370 } else {
3371 return true;
3372 }
3373 }
3374
Chiachang Wang96e1a0b2021-03-09 14:55:31 +08003375 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003376 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003377
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003378 if (CollectionUtils.contains(args, DIAG_ARG)) {
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003379 dumpNetworkDiagnostics(pw);
3380 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003381 } else if (CollectionUtils.contains(args, NETWORK_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003382 dumpNetworks(pw);
3383 return;
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003384 } else if (CollectionUtils.contains(args, REQUEST_ARG)) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003385 dumpNetworkRequests(pw);
3386 return;
Ken Chene6d511f2022-01-25 11:10:42 +08003387 } else if (CollectionUtils.contains(args, TRAFFICCONTROLLER_ARG)) {
3388 boolean verbose = !CollectionUtils.contains(args, SHORT_ARG);
3389 dumpTrafficController(pw, fd, verbose);
3390 return;
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003391 }
Erik Kline9647f382015-06-05 17:47:34 +09003392
Junyu Lai0da479b2022-04-20 15:06:29 +08003393 pw.println("NetworkProviders for:");
3394 pw.increaseIndent();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09003395 for (NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
Junyu Lai0da479b2022-04-20 15:06:29 +08003396 pw.println(npi.providerId + ": " + npi.name);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003397 }
Junyu Lai0da479b2022-04-20 15:06:29 +08003398 pw.decreaseIndent();
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07003399 pw.println();
3400
Chalard Jean5b409c72021-02-04 13:12:59 +09003401 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003402 pw.print("Active default network: ");
Chalard Jean5b409c72021-02-04 13:12:59 +09003403 if (defaultNai == null) {
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003404 pw.println("none");
3405 } else {
Chalard Jean5b409c72021-02-04 13:12:59 +09003406 pw.println(defaultNai.network.getNetId());
The Android Open Source Project28527d22009-03-03 19:31:44 -08003407 }
Dianne Hackborn5ac88162014-02-26 16:20:52 -08003408 pw.println();
3409
James Mattis8b298a02021-06-01 22:34:04 -07003410 pw.println("Current network preferences: ");
James Mattis45d81842021-01-10 14:24:24 -08003411 pw.increaseIndent();
James Mattis8b298a02021-06-01 22:34:04 -07003412 dumpNetworkPreferences(pw);
James Mattis45d81842021-01-10 14:24:24 -08003413 pw.decreaseIndent();
3414 pw.println();
3415
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003416 pw.println("Current Networks:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003417 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003418 dumpNetworks(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003419 pw.decreaseIndent();
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003420 pw.println();
Robert Greenwalt3eeb6032009-12-21 18:24:07 -08003421
junyulaif2c67e42018-08-07 19:50:45 +08003422 pw.println("Status for known UIDs:");
3423 pw.increaseIndent();
Sudheer Shanka9967d462021-03-18 19:09:25 +00003424 final int size = mUidBlockedReasons.size();
junyulaif2c67e42018-08-07 19:50:45 +08003425 for (int i = 0; i < size; i++) {
3426 // Don't crash if the array is modified while dumping in bugreports.
3427 try {
Sudheer Shanka9967d462021-03-18 19:09:25 +00003428 final int uid = mUidBlockedReasons.keyAt(i);
3429 final int blockedReasons = mUidBlockedReasons.valueAt(i);
3430 pw.println("UID=" + uid + " blockedReasons="
Sudheer Shankaf0ffc772021-04-21 07:23:54 +00003431 + Integer.toHexString(blockedReasons));
junyulaif2c67e42018-08-07 19:50:45 +08003432 } catch (ArrayIndexOutOfBoundsException e) {
3433 pw.println(" ArrayIndexOutOfBoundsException");
3434 } catch (ConcurrentModificationException e) {
3435 pw.println(" ConcurrentModificationException");
3436 }
3437 }
3438 pw.println();
3439 pw.decreaseIndent();
3440
Robert Greenwalta6d85c82014-05-13 15:36:27 -07003441 pw.println("Network Requests:");
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003442 pw.increaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003443 dumpNetworkRequests(pw);
Jeff Sharkeycf6ffaf2012-09-14 13:47:51 -07003444 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003445 pw.println();
Robert Greenwalt8e87f122010-02-11 18:18:40 -08003446
Junyu Lai0da479b2022-04-20 15:06:29 +08003447 pw.println("Network Offers:");
3448 pw.increaseIndent();
3449 for (final NetworkOfferInfo offerInfo : mNetworkOffers) {
3450 pw.println(offerInfo.offer);
3451 }
3452 pw.decreaseIndent();
3453 pw.println();
3454
Robert Greenwalt94e22142014-07-30 16:31:24 -07003455 mLegacyTypeTracker.dump(pw);
Robert Greenwalt94e22142014-07-30 16:31:24 -07003456
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003457 pw.println();
markchien5e866652019-09-30 14:40:57 +08003458 mKeepaliveTracker.dump(pw);
Robert Greenwalt0e80be12010-09-20 14:35:25 -07003459
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003460 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09003461 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti1e01f082016-03-03 17:53:46 +09003462
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003463 pw.println();
Lorenzo Colitti389a8142018-01-24 17:35:07 +09003464
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09003465 if (!CollectionUtils.contains(args, SHORT_ARG)) {
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003466 pw.println();
Erik Klineedf878b2015-07-09 18:24:03 +09003467 pw.println("mNetworkRequestInfoLogs (most recent first):");
3468 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003469 mNetworkRequestInfoLogs.reverseDump(pw);
Erik Klineedf878b2015-07-09 18:24:03 +09003470 pw.decreaseIndent();
Hugo Benichid159fdd2016-07-11 11:05:12 +09003471
3472 pw.println();
3473 pw.println("mNetworkInfoBlockingLogs (most recent first):");
3474 pw.increaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003475 mNetworkInfoBlockingLogs.reverseDump(pw);
Hugo Benichid159fdd2016-07-11 11:05:12 +09003476 pw.decreaseIndent();
Hugo Benichi47011212017-03-30 10:46:05 +09003477
3478 pw.println();
3479 pw.println("NetTransition WakeLock activity (most recent first):");
3480 pw.increaseIndent();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09003481 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
3482 pw.println("total releases: " + mTotalWakelockReleases);
3483 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
3484 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
3485 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
3486 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3487 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
3488 }
James Mattiscb1e0362021-04-06 17:07:42 -07003489 mWakelockLogs.reverseDump(pw);
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003490
3491 pw.println();
3492 pw.println("bandwidth update requests (by uid):");
3493 pw.increaseIndent();
3494 synchronized (mBandwidthRequests) {
3495 for (int i = 0; i < mBandwidthRequests.size(); i++) {
3496 pw.println("[" + mBandwidthRequests.keyAt(i)
3497 + "]: " + mBandwidthRequests.valueAt(i));
3498 }
3499 }
3500 pw.decreaseIndent();
James Mattiscb1e0362021-04-06 17:07:42 -07003501 pw.decreaseIndent();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07003502
James Mattiscb1e0362021-04-06 17:07:42 -07003503 pw.println();
3504 pw.println("mOemNetworkPreferencesLogs (most recent first):");
3505 pw.increaseIndent();
3506 mOemNetworkPreferencesLogs.reverseDump(pw);
Hugo Benichi47011212017-03-30 10:46:05 +09003507 pw.decreaseIndent();
Robert Greenwalt27ff7742015-06-23 15:03:33 -07003508 }
Remi NGUYEN VAN31c44d72019-02-18 11:20:28 +09003509
3510 pw.println();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00003511
3512 pw.println();
3513 pw.println("Permission Monitor:");
3514 pw.increaseIndent();
3515 mPermissionMonitor.dump(pw);
3516 pw.decreaseIndent();
lucaslin012f7a12021-01-21 02:04:35 +08003517
3518 pw.println();
3519 pw.println("Legacy network activity:");
3520 pw.increaseIndent();
3521 mNetworkActivityTracker.dump(pw);
3522 pw.decreaseIndent();
The Android Open Source Project28527d22009-03-03 19:31:44 -08003523 }
3524
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003525 private void dumpNetworks(IndentingPrintWriter pw) {
3526 for (NetworkAgentInfo nai : networksSortedById()) {
3527 pw.println(nai.toString());
3528 pw.increaseIndent();
Hungming Chenc6e00ea2022-05-18 22:36:20 +08003529 pw.println("Nat464Xlat:");
3530 pw.increaseIndent();
3531 nai.dumpNat464Xlat(pw);
3532 pw.decreaseIndent();
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003533 pw.println(String.format(
3534 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
3535 nai.numForegroundNetworkRequests(),
3536 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
3537 nai.numBackgroundNetworkRequests(),
3538 nai.numNetworkRequests()));
3539 pw.increaseIndent();
3540 for (int i = 0; i < nai.numNetworkRequests(); i++) {
3541 pw.println(nai.requestAt(i).toString());
3542 }
3543 pw.decreaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003544 pw.println("Inactivity Timers:");
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003545 pw.increaseIndent();
junyulai2b6f0c22021-02-03 20:15:30 +08003546 nai.dumpInactivityTimers(pw);
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003547 pw.decreaseIndent();
3548 pw.decreaseIndent();
3549 }
3550 }
3551
James Mattis8b298a02021-06-01 22:34:04 -07003552 private void dumpNetworkPreferences(IndentingPrintWriter pw) {
3553 if (!mProfileNetworkPreferences.isEmpty()) {
3554 pw.println("Profile preferences:");
3555 pw.increaseIndent();
Chalard Jean0606fc82022-12-14 20:34:43 +09003556 pw.println(mProfileNetworkPreferences);
James Mattis8b298a02021-06-01 22:34:04 -07003557 pw.decreaseIndent();
James Mattis45d81842021-01-10 14:24:24 -08003558 }
James Mattis8b298a02021-06-01 22:34:04 -07003559 if (!mOemNetworkPreferences.isEmpty()) {
3560 pw.println("OEM preferences:");
3561 pw.increaseIndent();
3562 pw.println(mOemNetworkPreferences);
3563 pw.decreaseIndent();
3564 }
3565 if (!mMobileDataPreferredUids.isEmpty()) {
3566 pw.println("Mobile data preferred UIDs:");
3567 pw.increaseIndent();
3568 pw.println(mMobileDataPreferredUids);
3569 pw.decreaseIndent();
3570 }
James Mattis45d81842021-01-10 14:24:24 -08003571
James Mattis8b298a02021-06-01 22:34:04 -07003572 pw.println("Default requests:");
3573 pw.increaseIndent();
3574 dumpPerAppDefaultRequests(pw);
3575 pw.decreaseIndent();
3576 }
3577
3578 private void dumpPerAppDefaultRequests(IndentingPrintWriter pw) {
James Mattis45d81842021-01-10 14:24:24 -08003579 for (final NetworkRequestInfo defaultRequest : mDefaultNetworkRequests) {
3580 if (mDefaultRequest == defaultRequest) {
3581 continue;
3582 }
3583
James Mattis8b298a02021-06-01 22:34:04 -07003584 final NetworkAgentInfo satisfier = defaultRequest.getSatisfier();
3585 final String networkOutput;
3586 if (null == satisfier) {
3587 networkOutput = "null";
3588 } else if (mNoServiceNetwork.equals(satisfier)) {
3589 networkOutput = "no service network";
James Mattis45d81842021-01-10 14:24:24 -08003590 } else {
James Mattis8b298a02021-06-01 22:34:04 -07003591 networkOutput = String.valueOf(satisfier.network.netId);
James Mattis45d81842021-01-10 14:24:24 -08003592 }
James Mattis8b298a02021-06-01 22:34:04 -07003593 final String asUidString = (defaultRequest.mAsUid == defaultRequest.mUid)
3594 ? "" : " asUid: " + defaultRequest.mAsUid;
3595 final String requestInfo = "Request: [uid/pid:" + defaultRequest.mUid + "/"
3596 + defaultRequest.mPid + asUidString + "]";
3597 final String satisfierOutput = "Satisfier: [" + networkOutput + "]"
3598 + " Preference order: " + defaultRequest.mPreferenceOrder
3599 + " Tracked UIDs: " + defaultRequest.getUids();
3600 pw.println(requestInfo + " - " + satisfierOutput);
James Mattis45d81842021-01-10 14:24:24 -08003601 }
3602 }
3603
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003604 private void dumpNetworkRequests(IndentingPrintWriter pw) {
Chiachang Wangeb256742021-07-27 14:00:17 +08003605 NetworkRequestInfo[] infos = null;
3606 while (infos == null) {
3607 try {
3608 infos = requestsSortedById();
3609 } catch (ConcurrentModificationException e) {
3610 // mNetworkRequests should only be accessed from handler thread, except dump().
3611 // As dump() is never called in normal usage, it would be needlessly expensive
3612 // to lock the collection only for its benefit. Instead, retry getting the
3613 // requests if ConcurrentModificationException is thrown during dump().
3614 }
3615 }
3616 for (NetworkRequestInfo nri : infos) {
Hugo Benichi5df91ce2018-09-03 08:32:56 +09003617 pw.println(nri.toString());
3618 }
3619 }
3620
Ken Chene6d511f2022-01-25 11:10:42 +08003621 private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
3622 boolean verbose) {
3623 try {
Motomu Utsumi310850f2022-09-02 12:48:20 +09003624 mBpfNetMaps.dump(pw, fd, verbose);
Ken Chene6d511f2022-01-25 11:10:42 +08003625 } catch (ServiceSpecificException e) {
3626 pw.println(e.getMessage());
3627 } catch (IOException e) {
3628 loge("Dump BPF maps failed, " + e);
3629 }
3630 }
3631
Chalard Jean524f0b12021-10-25 21:11:56 +09003632 private void dumpAllRequestInfoLogsToLogcat() {
3633 try (PrintWriter logPw = new PrintWriter(new Writer() {
3634 @Override
3635 public void write(final char[] cbuf, final int off, final int len) {
3636 // This method is called with 0-length and 1-length arrays for empty strings
3637 // or strings containing only the DEL character.
3638 if (len <= 1) return;
3639 Log.e(TAG, new String(cbuf, off, len));
3640 }
3641 @Override public void flush() {}
3642 @Override public void close() {}
3643 })) {
3644 mNetworkRequestInfoLogs.dump(logPw);
3645 }
3646 }
3647
Hugo Benichia480ba52018-09-03 08:19:02 +09003648 /**
3649 * Return an array of all current NetworkAgentInfos sorted by network id.
3650 */
3651 private NetworkAgentInfo[] networksSortedById() {
3652 NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003653 networks = mNetworkAgentInfos.toArray(networks);
Serik Beketayevec8ad212020-12-07 22:43:07 -08003654 Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
Hugo Benichia480ba52018-09-03 08:19:02 +09003655 return networks;
3656 }
3657
3658 /**
3659 * Return an array of all current NetworkRequest sorted by request id.
3660 */
James Mattis258ea3c2020-11-15 15:04:40 -08003661 @VisibleForTesting
James Mattisa152f882020-11-20 16:08:10 -08003662 NetworkRequestInfo[] requestsSortedById() {
Hugo Benichia480ba52018-09-03 08:19:02 +09003663 NetworkRequestInfo[] requests = new NetworkRequestInfo[0];
James Mattisa076c532020-12-02 14:12:41 -08003664 requests = getNrisFromGlobalRequests().toArray(requests);
James Mattis258ea3c2020-11-15 15:04:40 -08003665 // Sort the array based off the NRI containing the min requestId in its requests.
3666 Arrays.sort(requests,
3667 Comparator.comparingInt(nri -> Collections.min(nri.mRequests,
3668 Comparator.comparingInt(req -> req.requestId)).requestId
3669 )
3670 );
Hugo Benichia480ba52018-09-03 08:19:02 +09003671 return requests;
3672 }
3673
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003674 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Sreeram Ramachandran7c987162014-11-12 22:31:52 -08003675 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003676 if (officialNai != null && officialNai.equals(nai)) return true;
3677 if (officialNai != null || VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003678 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalta6fd83d2014-08-19 18:58:04 -07003679 " - " + nai);
3680 }
3681 return false;
3682 }
3683
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003684 private boolean isDisconnectRequest(Message msg) {
3685 if (msg.what != NetworkAgent.EVENT_NETWORK_INFO_CHANGED) return false;
3686 final NetworkInfo info = (NetworkInfo) ((Pair) msg.obj).second;
3687 return info.getState() == NetworkInfo.State.DISCONNECTED;
3688 }
3689
Robert Greenwalt2034b912009-08-12 16:08:25 -07003690 // must be stateless - things change under us.
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003691 private class NetworkStateTrackerHandler extends Handler {
3692 public NetworkStateTrackerHandler(Looper looper) {
Wink Saville775aad62010-09-02 19:23:52 -07003693 super(looper);
3694 }
3695
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003696 private void maybeHandleNetworkAgentMessage(Message msg) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003697 final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
3698 final NetworkAgentInfo nai = arg.first;
3699 if (!mNetworkAgentInfos.contains(nai)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003700 if (VDBG) {
Hugo Benichi47011212017-03-30 10:46:05 +09003701 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003702 }
3703 return;
3704 }
3705
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003706 // If the network has been destroyed, the only thing that it can do is disconnect.
Chalard Jean254bd162022-08-25 13:04:51 +09003707 if (nai.isDestroyed() && !isDisconnectRequest(msg)) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003708 return;
3709 }
3710
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003711 switch (msg.what) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003712 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Chalard Jean39b12d42022-02-27 12:08:49 +09003713 nai.setDeclaredCapabilities((NetworkCapabilities) arg.second);
3714 final NetworkCapabilities sanitized =
3715 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator);
Chalard Jeanda7fe572022-02-01 23:47:23 +09003716 maybeUpdateWifiRoamTimestamp(nai, sanitized);
Chalard Jeanaa5bc622022-02-26 21:34:48 +09003717 updateCapabilities(nai.getScore(), nai, sanitized);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07003718 break;
3719 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003720 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003721 LinkProperties newLp = (LinkProperties) arg.second;
Lorenzo Colitti18a58462020-04-16 01:52:40 +09003722 processLinkPropertiesFromAgent(nai, newLp);
3723 handleUpdateLinkProperties(nai, newLp);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003724 break;
3725 }
3726 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003727 NetworkInfo info = (NetworkInfo) arg.second;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003728 updateNetworkInfo(nai, info);
3729 break;
3730 }
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003731 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Chalard Jean28018572020-12-21 18:36:52 +09003732 updateNetworkScore(nai, (NetworkScore) arg.second);
Robert Greenwalt06c734e2014-05-27 13:20:24 -07003733 break;
3734 }
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003735 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Chalard Jean254bd162022-08-25 13:04:51 +09003736 if (nai.everConnected()) {
Lorenzo Colittib882c542019-06-04 14:37:26 +09003737 loge("ERROR: cannot call explicitlySelected on already-connected network");
Chalard Jeanfbc54672021-01-20 20:47:32 +09003738 // Note that if the NAI had been connected, this would affect the
3739 // score, and therefore would require re-mixing the score and performing
3740 // a rematch.
Paul Jensen0fa1abf2014-09-26 10:10:22 -04003741 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003742 nai.networkAgentConfig.explicitlySelected = toBool(msg.arg1);
3743 nai.networkAgentConfig.acceptUnvalidated = toBool(msg.arg1) && toBool(msg.arg2);
lucaslin2240ef62019-03-12 13:08:03 +08003744 // Mark the network as temporarily accepting partial connectivity so that it
3745 // will be validated (and possibly become default) even if it only provides
3746 // partial internet access. Note that if user connects to partial connectivity
3747 // and choose "don't ask again", then wifi disconnected by some reasons(maybe
3748 // out of wifi coverage) and if the same wifi is available again, the device
3749 // will auto connect to this wifi even though the wifi has "no internet".
3750 // TODO: Evaluate using a separate setting in IpMemoryStore.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003751 nai.networkAgentConfig.acceptPartialConnectivity = toBool(msg.arg2);
Robert Greenwalte06ea4b2014-09-07 16:50:01 -07003752 break;
3753 }
junyulai011b1f12019-01-03 18:50:15 +08003754 case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09003755 mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09003756 break;
3757 }
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003758 case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09003759 // TODO: prevent loops, e.g., if a network declares itself as underlying.
Remi NGUYEN VAN28d69fc2020-12-25 12:45:46 +09003760 final List<Network> underlying = (List<Network>) arg.second;
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09003761
3762 if (isLegacyLockdownNai(nai)
3763 && (underlying == null || underlying.size() != 1)) {
3764 Log.wtf(TAG, "Legacy lockdown VPN " + nai.toShortString()
3765 + " must have exactly one underlying network: " + underlying);
3766 }
3767
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003768 final Network[] oldUnderlying = nai.declaredUnderlyingNetworks;
3769 nai.declaredUnderlyingNetworks = (underlying != null)
3770 ? underlying.toArray(new Network[0]) : null;
3771
3772 if (!Arrays.equals(oldUnderlying, nai.declaredUnderlyingNetworks)) {
3773 if (DBG) {
3774 log(nai.toShortString() + " changed underlying networks to "
3775 + Arrays.toString(nai.declaredUnderlyingNetworks));
3776 }
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003777 updateCapabilitiesForNetwork(nai);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003778 notifyIfacesChangedForNetworkStats();
3779 }
Daniel Brightf9e945b2020-06-15 16:10:01 -07003780 break;
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09003781 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003782 case NetworkAgent.EVENT_TEARDOWN_DELAY_CHANGED: {
3783 if (msg.arg1 >= 0 && msg.arg1 <= NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3784 nai.teardownDelayMs = msg.arg1;
3785 } else {
3786 logwtf(nai.toShortString() + " set invalid teardown delay " + msg.arg1);
3787 }
Chalard Jean550b5212021-03-05 23:07:53 +09003788 break;
3789 }
3790 case NetworkAgent.EVENT_LINGER_DURATION_CHANGED: {
3791 nai.setLingerDuration((int) arg.second);
3792 break;
Lorenzo Colittid5385c42021-03-11 01:32:09 +09003793 }
Tyler Wear72388212021-09-09 14:49:02 -07003794 case NetworkAgent.EVENT_ADD_DSCP_POLICY: {
3795 DscpPolicy policy = (DscpPolicy) arg.second;
3796 if (mDscpPolicyTracker != null) {
3797 mDscpPolicyTracker.addDscpPolicy(nai, policy);
3798 }
3799 break;
3800 }
3801 case NetworkAgent.EVENT_REMOVE_DSCP_POLICY: {
3802 if (mDscpPolicyTracker != null) {
3803 mDscpPolicyTracker.removeDscpPolicy(nai, (int) arg.second);
3804 }
3805 break;
3806 }
3807 case NetworkAgent.EVENT_REMOVE_ALL_DSCP_POLICIES: {
3808 if (mDscpPolicyTracker != null) {
Tyler Wear3ad80892022-02-03 15:14:44 -08003809 mDscpPolicyTracker.removeAllDscpPolicies(nai, true);
Tyler Wear72388212021-09-09 14:49:02 -07003810 }
3811 break;
3812 }
Lorenzo Colittia63e2342022-03-23 23:17:16 +09003813 case NetworkAgent.EVENT_UNREGISTER_AFTER_REPLACEMENT: {
Lorenzo Colitti82350ea2022-09-16 19:53:03 +09003814 if (!nai.isCreated()) {
3815 Log.d(TAG, "unregisterAfterReplacement on uncreated " + nai.toShortString()
3816 + ", tearing down instead");
3817 teardownUnneededNetwork(nai);
3818 break;
3819 }
3820
3821 if (nai.isDestroyed()) {
3822 Log.d(TAG, "unregisterAfterReplacement on destroyed " + nai.toShortString()
3823 + ", ignoring");
3824 break;
3825 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003826
3827 final int timeoutMs = (int) arg.second;
3828 if (timeoutMs < 0 || timeoutMs > NetworkAgent.MAX_TEARDOWN_DELAY_MS) {
3829 Log.e(TAG, "Invalid network replacement timer " + timeoutMs
3830 + ", must be between 0 and " + NetworkAgent.MAX_TEARDOWN_DELAY_MS);
3831 }
3832
3833 // Marking a network awaiting replacement is used to ensure that any requests
3834 // satisfied by the network do not switch to another network until a
3835 // replacement is available or the wait for a replacement times out.
3836 // If the network is inactive (i.e., nascent or lingering), then there are no
3837 // such requests, and there is no point keeping it. Just tear it down.
3838 // Note that setLingerDuration(0) cannot be used to do this because the network
3839 // could be nascent.
3840 nai.clearInactivityState();
3841 if (unneeded(nai, UnneededFor.TEARDOWN)) {
3842 Log.d(TAG, nai.toShortString()
3843 + " marked awaiting replacement is unneeded, tearing down instead");
3844 teardownUnneededNetwork(nai);
3845 break;
3846 }
3847
3848 Log.d(TAG, "Marking " + nai.toShortString()
3849 + " destroyed, awaiting replacement within " + timeoutMs + "ms");
3850 destroyNativeNetwork(nai);
3851
3852 // TODO: deduplicate this call with the one in disconnectAndDestroyNetwork.
3853 // This is not trivial because KeepaliveTracker#handleStartKeepalive does not
3854 // consider the fact that the network could already have disconnected or been
3855 // destroyed. Fix the code to send ERROR_INVALID_NETWORK when this happens
3856 // (taking care to ensure no dup'd FD leaks), then remove the code duplication
3857 // and move this code to a sensible location (destroyNativeNetwork perhaps?).
3858 mKeepaliveTracker.handleStopAllKeepalives(nai,
3859 SocketKeepalive.ERROR_INVALID_NETWORK);
3860
3861 nai.updateScoreForNetworkAgentUpdate();
3862 // This rematch is almost certainly not going to result in any changes, because
3863 // the destroyed flag is only just above the "current satisfier wins"
3864 // tie-breaker. But technically anything that affects scoring should rematch.
3865 rematchAllNetworksAndRequests();
3866 mHandler.postDelayed(() -> nai.disconnect(), timeoutMs);
3867 break;
3868 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003869 }
3870 }
3871
3872 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003873 final int netId = msg.arg2;
3874 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09003875 // If a network has already been destroyed, all NetworkMonitor updates are ignored.
Chalard Jean254bd162022-08-25 13:04:51 +09003876 if (nai != null && nai.isDestroyed()) return true;
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003877 switch (msg.what) {
3878 default:
3879 return false;
lucasline117e2e2019-10-22 18:27:33 +08003880 case EVENT_PROBE_STATUS_CHANGED: {
lucasline117e2e2019-10-22 18:27:33 +08003881 if (nai == null) {
3882 break;
3883 }
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003884 final int probesCompleted = ((Pair<Integer, Integer>) msg.obj).first;
3885 final int probesSucceeded = ((Pair<Integer, Integer>) msg.obj).second;
lucasline117e2e2019-10-22 18:27:33 +08003886 final boolean probePrivateDnsCompleted =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003887 ((probesCompleted & NETWORK_VALIDATION_PROBE_PRIVDNS) != 0);
lucasline117e2e2019-10-22 18:27:33 +08003888 final boolean privateDnsBroken =
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09003889 ((probesSucceeded & NETWORK_VALIDATION_PROBE_PRIVDNS) == 0);
lucasline117e2e2019-10-22 18:27:33 +08003890 if (probePrivateDnsCompleted) {
3891 if (nai.networkCapabilities.isPrivateDnsBroken() != privateDnsBroken) {
3892 nai.networkCapabilities.setPrivateDnsBroken(privateDnsBroken);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003893 updateCapabilitiesForNetwork(nai);
lucasline117e2e2019-10-22 18:27:33 +08003894 }
3895 // Only show the notification when the private DNS is broken and the
3896 // PRIVATE_DNS_BROKEN notification hasn't shown since last valid.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003897 if (privateDnsBroken && !nai.networkAgentConfig.hasShownBroken) {
lucasline117e2e2019-10-22 18:27:33 +08003898 showNetworkNotification(nai, NotificationType.PRIVATE_DNS_BROKEN);
3899 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003900 nai.networkAgentConfig.hasShownBroken = privateDnsBroken;
lucasline117e2e2019-10-22 18:27:33 +08003901 } else if (nai.networkCapabilities.isPrivateDnsBroken()) {
3902 // If probePrivateDnsCompleted is false but nai.networkCapabilities says
3903 // private DNS is broken, it means this network is being reevaluated.
3904 // Either probing private DNS is not necessary any more or it hasn't been
3905 // done yet. In either case, the networkCapabilities should be updated to
3906 // reflect the new status.
3907 nai.networkCapabilities.setPrivateDnsBroken(false);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09003908 updateCapabilitiesForNetwork(nai);
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003909 nai.networkAgentConfig.hasShownBroken = false;
lucasline117e2e2019-10-22 18:27:33 +08003910 }
3911 break;
3912 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003913 case EVENT_NETWORK_TESTED: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003914 final NetworkTestedResults results = (NetworkTestedResults) msg.obj;
3915
Erik Kline31b4a9e2018-01-11 21:07:29 +09003916 if (nai == null) break;
3917
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003918 handleNetworkTested(nai, results.mTestResult,
3919 (results.mRedirectUrl == null) ? "" : results.mRedirectUrl);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07003920 break;
3921 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003922 case EVENT_PROVISIONING_NOTIFICATION: {
Hugo Benichif4210292017-04-21 15:07:12 +09003923 final boolean visible = toBool(msg.arg1);
Calvin Ondada1452016-10-11 15:10:46 -07003924 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen53f08952015-06-16 14:27:36 -04003925 if (!visible) {
lucaslinb1e8e382019-01-24 15:55:30 +08003926 // Only clear SIGN_IN and NETWORK_SWITCH notifications here, or else other
lucaslin2240ef62019-03-12 13:08:03 +08003927 // notifications belong to the same network may be cleared unexpectedly.
lucaslinb1e8e382019-01-24 15:55:30 +08003928 mNotifier.clearNotification(netId, NotificationType.SIGN_IN);
3929 mNotifier.clearNotification(netId, NotificationType.NETWORK_SWITCH);
Paul Jensen26dd0022014-07-15 12:07:36 -04003930 } else {
Paul Jensen7844b812014-08-25 22:45:39 -04003931 if (nai == null) {
3932 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
3933 break;
3934 }
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003935 if (!nai.networkAgentConfig.provisioningNotificationDisabled) {
Lorenzo Colittiddc5fd82016-08-22 16:46:40 +09003936 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09003937 (PendingIntent) msg.obj,
3938 nai.networkAgentConfig.explicitlySelected);
fionaxu5310c302016-05-23 16:33:16 -07003939 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003940 }
Paul Jensen239ce0b2014-05-15 10:33:05 -04003941 break;
3942 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09003943 case EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
Erik Kline31b4a9e2018-01-11 21:07:29 +09003944 if (nai == null) break;
3945
Erik Kline9a62f012018-03-21 07:18:33 -07003946 updatePrivateDns(nai, (PrivateDnsConfig) msg.obj);
Erik Kline31b4a9e2018-01-11 21:07:29 +09003947 break;
3948 }
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003949 case EVENT_CAPPORT_DATA_CHANGED: {
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003950 if (nai == null) break;
Hai Shalome58bdc62021-01-11 18:45:34 -08003951 handleCapportApiDataUpdate(nai, (CaptivePortalData) msg.obj);
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09003952 break;
3953 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07003954 }
Lorenzo Colittib54bea92016-04-05 17:52:16 +09003955 return true;
3956 }
3957
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003958 private void handleNetworkTested(
3959 @NonNull NetworkAgentInfo nai, int testResult, @NonNull String redirectUrl) {
Chalard Jean5fb43c72022-09-08 19:03:14 +09003960 final boolean valid = (testResult & NETWORK_VALIDATION_RESULT_VALID) != 0;
3961 final boolean partial = (testResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0;
Chalard Jean8a9061f2022-09-22 16:25:10 +09003962 final boolean portal = !TextUtils.isEmpty(redirectUrl);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003963
3964 // If there is any kind of working networking, then the NAI has been evaluated
3965 // once. {@see NetworkAgentInfo#setEvaluated}, which returns whether this is
3966 // the first time this ever happened.
Chalard Jean8a9061f2022-09-22 16:25:10 +09003967 final boolean someConnectivity = (valid || partial || portal);
Chalard Jean5fb43c72022-09-08 19:03:14 +09003968 final boolean becameEvaluated = someConnectivity && nai.setEvaluated();
Chalard Jeane63c42f2022-09-16 19:31:45 +09003969 // Because of b/245893397, if the score is updated when updateCapabilities is called,
3970 // any callback that receives onAvailable for that rematch receives an extra caps
3971 // callback. To prevent that, update the score in the agent so the updates below won't
3972 // see an update to both caps and score at the same time.
3973 // TODO : fix b/245893397 and remove this.
Chalard Jean5fb43c72022-09-08 19:03:14 +09003974 if (becameEvaluated) nai.updateScoreForNetworkAgentUpdate();
3975
he_won.hwang881307a2022-03-15 21:23:52 +09003976 if (!valid && shouldIgnoreValidationFailureAfterRoam(nai)) {
3977 // Assume the validation failure is due to a temporary failure after roaming
3978 // and ignore it. NetworkMonitor will continue to retry validation. If it
3979 // continues to fail after the block timeout expires, the network will be
3980 // marked unvalidated. If it succeeds, then validation state will not change.
3981 return;
3982 }
3983
Chalard Jean254bd162022-08-25 13:04:51 +09003984 final boolean wasValidated = nai.isValidated();
3985 final boolean wasPartial = nai.partialConnectivity();
Chalard Jean8a9061f2022-09-22 16:25:10 +09003986 final boolean wasPortal = nai.captivePortalDetected();
3987 nai.setPartialConnectivity(partial);
3988 nai.setCaptivePortalDetected(portal);
3989 nai.updateScoreForNetworkAgentUpdate();
3990 final boolean partialConnectivityChanged = (wasPartial != partial);
3991 final boolean portalChanged = (wasPortal != portal);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003992
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003993 if (DBG) {
3994 final String logMsg = !TextUtils.isEmpty(redirectUrl)
3995 ? " with redirect to " + redirectUrl
3996 : "";
Chalard Jean49707572019-12-10 21:07:02 +09003997 log(nai.toShortString() + " validation " + (valid ? "passed" : "failed") + logMsg);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08003998 }
Chalard Jean8a9061f2022-09-22 16:25:10 +09003999 if (valid != wasValidated) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09004000 final FullScore oldScore = nai.getScore();
Chalard Jean254bd162022-08-25 13:04:51 +09004001 nai.setValidated(valid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004002 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004003 if (valid) {
4004 handleFreshlyValidatedNetwork(nai);
4005 // Clear NO_INTERNET, PRIVATE_DNS_BROKEN, PARTIAL_CONNECTIVITY and
4006 // LOST_INTERNET notifications if network becomes valid.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004007 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004008 NotificationType.NO_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004009 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004010 NotificationType.LOST_INTERNET);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004011 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004012 NotificationType.PARTIAL_CONNECTIVITY);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004013 mNotifier.clearNotification(nai.network.getNetId(),
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004014 NotificationType.PRIVATE_DNS_BROKEN);
4015 // If network becomes valid, the hasShownBroken should be reset for
4016 // that network so that the notification will be fired when the private
4017 // DNS is broken again.
4018 nai.networkAgentConfig.hasShownBroken = false;
4019 }
4020 } else if (partialConnectivityChanged) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09004021 updateCapabilitiesForNetwork(nai);
Chalard Jean8a9061f2022-09-22 16:25:10 +09004022 } else if (portalChanged) {
4023 if (portal && ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_AVOID
4024 == getCaptivePortalMode()) {
4025 if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
4026 nai.onPreventAutomaticReconnect();
4027 teardownUnneededNetwork(nai);
4028 return;
4029 } else {
4030 updateCapabilitiesForNetwork(nai);
4031 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09004032 } else if (becameEvaluated) {
4033 // If valid or partial connectivity changed, updateCapabilities* has
4034 // done the rematch.
4035 rematchAllNetworksAndRequests();
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004036 }
4037 updateInetCondition(nai);
Chalard Jean5fb43c72022-09-08 19:03:14 +09004038
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004039 // Let the NetworkAgent know the state of its network
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004040 // TODO: Evaluate to update partial connectivity to status to NetworkAgent.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004041 nai.onValidationStatusChanged(
4042 valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
4043 redirectUrl);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004044
4045 // If NetworkMonitor detects partial connectivity before
Chalard Jean5fb43c72022-09-08 19:03:14 +09004046 // EVENT_INITIAL_EVALUATION_TIMEOUT arrives, show the partial connectivity notification
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004047 // immediately. Re-notify partial connectivity silently if no internet
4048 // notification already there.
Chalard Jean254bd162022-08-25 13:04:51 +09004049 if (!wasPartial && nai.partialConnectivity()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004050 // Remove delayed message if there is a pending message.
Chalard Jean5fb43c72022-09-08 19:03:14 +09004051 mHandler.removeMessages(EVENT_INITIAL_EVALUATION_TIMEOUT, nai.network);
4052 handleInitialEvaluationTimeout(nai.network);
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004053 }
4054
Chalard Jean254bd162022-08-25 13:04:51 +09004055 if (wasValidated && !nai.isValidated()) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004056 handleNetworkUnvalidated(nai);
4057 }
4058 }
4059
Calvin Ondada1452016-10-11 15:10:46 -07004060 private int getCaptivePortalMode() {
4061 return Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08004062 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE,
4063 ConnectivitySettingsManager.CAPTIVE_PORTAL_MODE_PROMPT);
Calvin Ondada1452016-10-11 15:10:46 -07004064 }
4065
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004066 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
4067 switch (msg.what) {
4068 default:
4069 return false;
4070 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
4071 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4072 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
4073 handleLingerComplete(nai);
4074 }
4075 break;
4076 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004077 case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
4078 handleNetworkAgentRegistered(msg);
4079 break;
4080 }
4081 case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
4082 handleNetworkAgentDisconnected(msg);
4083 break;
4084 }
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004085 }
4086 return true;
4087 }
4088
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004089 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +09004090 public void handleMessage(@NonNull Message msg) {
lifraf3a3492021-03-10 13:58:14 +08004091 if (!maybeHandleNetworkMonitorMessage(msg)
Remi NGUYEN VAN82b5bb62020-01-14 19:48:18 +09004092 && !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colittib54bea92016-04-05 17:52:16 +09004093 maybeHandleNetworkAgentMessage(msg);
4094 }
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07004095 }
4096 }
4097
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004098 private class NetworkMonitorCallbacks extends INetworkMonitorCallbacks.Stub {
Chalard Jean7284daa2019-05-30 14:58:29 +09004099 private final int mNetId;
4100 private final AutodestructReference<NetworkAgentInfo> mNai;
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004101
4102 private NetworkMonitorCallbacks(NetworkAgentInfo nai) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004103 mNetId = nai.network.getNetId();
Chalard Jeanfbab6d42019-09-26 18:03:47 +09004104 mNai = new AutodestructReference<>(nai);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004105 }
4106
4107 @Override
4108 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
4109 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT,
Chalard Jean7284daa2019-05-30 14:58:29 +09004110 new Pair<>(mNai.getAndDestroy(), networkMonitor)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004111 }
4112
4113 @Override
4114 public void notifyNetworkTested(int testResult, @Nullable String redirectUrl) {
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004115 // Legacy version of notifyNetworkTestedWithExtras.
4116 // Would only be called if the system has a NetworkStack module older than the
4117 // framework, which does not happen in practice.
Aaron Huang6616df32020-10-30 22:04:25 +08004118 Log.wtf(TAG, "Deprecated notifyNetworkTested called: no action taken");
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004119 }
4120
4121 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004122 public void notifyNetworkTestedWithExtras(NetworkTestResultParcelable p) {
Remi NGUYEN VAN455b93d2020-04-24 20:56:39 +09004123 // Notify mTrackerHandler and mConnectivityDiagnosticsHandler of the event. Both use
4124 // the same looper so messages will be processed in sequence.
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004125 final Message msg = mTrackerHandler.obtainMessage(
4126 EVENT_NETWORK_TESTED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004127 0, mNetId,
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004128 new NetworkTestedResults(
4129 mNetId, p.result, p.timestampMillis, p.redirectUrl));
Cody Kesting83bb5fa2020-01-05 14:06:39 -08004130 mTrackerHandler.sendMessage(msg);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004131
4132 // Invoke ConnectivityReport generation for this Network test event.
4133 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(mNetId);
4134 if (nai == null) return;
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004135
Cody Kestingf1120be2020-08-03 18:01:40 -07004136 // NetworkMonitor reports the network validation result as a bitmask while
4137 // ConnectivityDiagnostics treats this value as an int. Convert the result to a single
4138 // logical value for ConnectivityDiagnostics.
4139 final int validationResult = networkMonitorValidationResultToConnDiagsValidationResult(
4140 p.result);
4141
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004142 final PersistableBundle extras = new PersistableBundle();
Cody Kestingf1120be2020-08-03 18:01:40 -07004143 extras.putInt(KEY_NETWORK_VALIDATION_RESULT, validationResult);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004144 extras.putInt(KEY_NETWORK_PROBES_SUCCEEDED_BITMASK, p.probesSucceeded);
4145 extras.putInt(KEY_NETWORK_PROBES_ATTEMPTED_BITMASK, p.probesAttempted);
4146
Aaron Huang959d3642021-01-21 15:47:41 +08004147 ConnectivityReportEvent reportEvent =
4148 new ConnectivityReportEvent(p.timestampMillis, nai, extras);
4149 final Message m = mConnectivityDiagnosticsHandler.obtainMessage(
Lorenzo Colitti0261ced2022-02-18 00:23:56 +09004150 ConnectivityDiagnosticsHandler.CMD_SEND_CONNECTIVITY_REPORT, reportEvent);
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004151 mConnectivityDiagnosticsHandler.sendMessage(m);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004152 }
4153
4154 @Override
4155 public void notifyPrivateDnsConfigResolved(PrivateDnsConfigParcel config) {
4156 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4157 EVENT_PRIVATE_DNS_CONFIG_RESOLVED,
Chalard Jean7284daa2019-05-30 14:58:29 +09004158 0, mNetId, PrivateDnsConfig.fromParcel(config)));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004159 }
4160
4161 @Override
lucasline117e2e2019-10-22 18:27:33 +08004162 public void notifyProbeStatusChanged(int probesCompleted, int probesSucceeded) {
4163 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4164 EVENT_PROBE_STATUS_CHANGED,
Lorenzo Colittid1b11dc2022-02-17 14:28:53 +09004165 0, mNetId, new Pair<>(probesCompleted, probesSucceeded)));
lucasline117e2e2019-10-22 18:27:33 +08004166 }
4167
4168 @Override
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004169 public void notifyCaptivePortalDataChanged(CaptivePortalData data) {
4170 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4171 EVENT_CAPPORT_DATA_CHANGED,
4172 0, mNetId, data));
4173 }
4174
4175 @Override
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004176 public void showProvisioningNotification(String action, String packageName) {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004177 final Intent intent = new Intent(action);
Remi NGUYEN VAN794c7f22019-02-07 21:29:57 +09004178 intent.setPackage(packageName);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004179
4180 final PendingIntent pendingIntent;
4181 // Only the system server can register notifications with package "android"
4182 final long token = Binder.clearCallingIdentity();
4183 try {
paulhu7746e4e2020-06-09 19:07:03 +08004184 pendingIntent = PendingIntent.getBroadcast(
4185 mContext,
4186 0 /* requestCode */,
4187 intent,
4188 PendingIntent.FLAG_IMMUTABLE);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004189 } finally {
4190 Binder.restoreCallingIdentity(token);
4191 }
4192 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
4193 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_SHOW,
Chalard Jean7284daa2019-05-30 14:58:29 +09004194 mNetId, pendingIntent));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004195 }
4196
4197 @Override
4198 public void hideProvisioningNotification() {
4199 mTrackerHandler.sendMessage(mTrackerHandler.obtainMessage(
Chalard Jean7284daa2019-05-30 14:58:29 +09004200 EVENT_PROVISIONING_NOTIFICATION, PROVISIONING_NOTIFICATION_HIDE, mNetId));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004201 }
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004202
4203 @Override
Remi NGUYEN VAN9b647ca2020-04-15 18:39:28 +09004204 public void notifyDataStallSuspected(DataStallReportParcelable p) {
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004205 ConnectivityService.this.notifyDataStallSuspected(p, mNetId);
Cody Kestingb12ad4c2020-01-06 16:55:35 -08004206 }
4207
4208 @Override
Remi NGUYEN VAN683df1d2019-04-05 15:15:48 +09004209 public int getInterfaceVersion() {
4210 return this.VERSION;
4211 }
Paul Trautrim79a9c8c2020-01-23 14:55:57 +09004212
4213 @Override
4214 public String getInterfaceHash() {
4215 return this.HASH;
4216 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004217 }
4218
Cody Kestingf1120be2020-08-03 18:01:40 -07004219 /**
4220 * Converts the given NetworkMonitor-specific validation result bitmask to a
4221 * ConnectivityDiagnostics-specific validation result int.
4222 */
4223 private int networkMonitorValidationResultToConnDiagsValidationResult(int validationResult) {
4224 if ((validationResult & NETWORK_VALIDATION_RESULT_SKIPPED) != 0) {
4225 return ConnectivityReport.NETWORK_VALIDATION_RESULT_SKIPPED;
4226 }
4227 if ((validationResult & NETWORK_VALIDATION_RESULT_VALID) == 0) {
4228 return ConnectivityReport.NETWORK_VALIDATION_RESULT_INVALID;
4229 }
4230 return (validationResult & NETWORK_VALIDATION_RESULT_PARTIAL) != 0
4231 ? ConnectivityReport.NETWORK_VALIDATION_RESULT_PARTIALLY_VALID
4232 : ConnectivityReport.NETWORK_VALIDATION_RESULT_VALID;
4233 }
4234
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004235 private void notifyDataStallSuspected(DataStallReportParcelable p, int netId) {
Cody Kestingb37958e2020-05-15 10:36:01 -07004236 log("Data stall detected with methods: " + p.detectionMethod);
4237
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004238 final PersistableBundle extras = new PersistableBundle();
Cody Kestingb37958e2020-05-15 10:36:01 -07004239 int detectionMethod = 0;
4240 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
4241 extras.putInt(KEY_DNS_CONSECUTIVE_TIMEOUTS, p.dnsConsecutiveTimeouts);
4242 detectionMethod |= DETECTION_METHOD_DNS_EVENTS;
4243 }
4244 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
4245 extras.putInt(KEY_TCP_PACKET_FAIL_RATE, p.tcpPacketFailRate);
4246 extras.putInt(KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS,
4247 p.tcpMetricsCollectionPeriodMillis);
4248 detectionMethod |= DETECTION_METHOD_TCP_METRICS;
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004249 }
4250
Cody Kestingf53a0752020-04-15 12:33:28 -07004251 final Message msg = mConnectivityDiagnosticsHandler.obtainMessage(
Cody Kestingf5cc4ea2020-05-11 10:06:51 -07004252 ConnectivityDiagnosticsHandler.EVENT_DATA_STALL_SUSPECTED, detectionMethod, netId,
Aaron Huang959d3642021-01-21 15:47:41 +08004253 new Pair<>(p.timestampMillis, extras));
Cody Kestingf53a0752020-04-15 12:33:28 -07004254
4255 // NetworkStateTrackerHandler currently doesn't take any actions based on data
4256 // stalls so send the message directly to ConnectivityDiagnosticsHandler and avoid
4257 // the cost of going through two handlers.
4258 mConnectivityDiagnosticsHandler.sendMessage(msg);
4259 }
4260
Cody Kestingb37958e2020-05-15 10:36:01 -07004261 private boolean hasDataStallDetectionMethod(DataStallReportParcelable p, int detectionMethod) {
4262 return (p.detectionMethod & detectionMethod) != 0;
4263 }
4264
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004265 private boolean networkRequiresPrivateDnsValidation(NetworkAgentInfo nai) {
4266 return isPrivateDnsValidationRequired(nai.networkCapabilities);
Erik Kline9a62f012018-03-21 07:18:33 -07004267 }
4268
Erik Klinea73af002018-06-26 18:53:43 +09004269 private void handleFreshlyValidatedNetwork(NetworkAgentInfo nai) {
4270 if (nai == null) return;
4271 // If the Private DNS mode is opportunistic, reprogram the DNS servers
4272 // in order to restart a validation pass from within netd.
4273 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4274 if (cfg.useTls && TextUtils.isEmpty(cfg.hostname)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08004275 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Klinea73af002018-06-26 18:53:43 +09004276 }
4277 }
4278
Erik Kline31b4a9e2018-01-11 21:07:29 +09004279 private void handlePrivateDnsSettingsChanged() {
4280 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
4281
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004282 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Erik Kline9a62f012018-03-21 07:18:33 -07004283 handlePerNetworkPrivateDnsConfig(nai, cfg);
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004284 if (networkRequiresPrivateDnsValidation(nai)) {
dalyk1720e542018-03-05 12:42:22 -05004285 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4286 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09004287 }
4288 }
4289
Erik Kline9a62f012018-03-21 07:18:33 -07004290 private void handlePerNetworkPrivateDnsConfig(NetworkAgentInfo nai, PrivateDnsConfig cfg) {
4291 // Private DNS only ever applies to networks that might provide
4292 // Internet access and therefore also require validation.
Lorenzo Colitti2fca7e32019-03-22 00:28:28 +09004293 if (!networkRequiresPrivateDnsValidation(nai)) return;
Erik Kline31b4a9e2018-01-11 21:07:29 +09004294
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09004295 // Notify the NetworkAgentInfo/NetworkMonitor in case NetworkMonitor needs to cancel or
Erik Kline9a62f012018-03-21 07:18:33 -07004296 // schedule DNS resolutions. If a DNS resolution is required the
4297 // result will be sent back to us.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004298 nai.networkMonitor().notifyPrivateDnsChanged(cfg.toParcel());
Erik Kline9a62f012018-03-21 07:18:33 -07004299
4300 // With Private DNS bypass support, we can proceed to update the
4301 // Private DNS config immediately, even if we're in strict mode
4302 // and have not yet resolved the provider name into a set of IPs.
4303 updatePrivateDns(nai, cfg);
4304 }
4305
4306 private void updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
4307 mDnsManager.updatePrivateDns(nai.network, newCfg);
Serik Beketayevec8ad212020-12-07 22:43:07 -08004308 updateDnses(nai.linkProperties, null, nai.network.getNetId());
Erik Kline31b4a9e2018-01-11 21:07:29 +09004309 }
4310
dalyk1720e542018-03-05 12:42:22 -05004311 private void handlePrivateDnsValidationUpdate(PrivateDnsValidationUpdate update) {
4312 NetworkAgentInfo nai = getNetworkAgentInfoForNetId(update.netId);
4313 if (nai == null) {
4314 return;
4315 }
4316 mDnsManager.updatePrivateDnsValidation(update);
4317 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4318 }
4319
paulhu7c0a2e62021-01-08 00:51:49 +08004320 private void handleNat64PrefixEvent(int netId, int operation, String prefixAddress,
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004321 int prefixLength) {
4322 NetworkAgentInfo nai = mNetworkForNetId.get(netId);
4323 if (nai == null) return;
4324
paulhu7c0a2e62021-01-08 00:51:49 +08004325 log(String.format("NAT64 prefix changed on netId %d: operation=%d, %s/%d",
4326 netId, operation, prefixAddress, prefixLength));
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004327
4328 IpPrefix prefix = null;
paulhu7c0a2e62021-01-08 00:51:49 +08004329 if (operation == IDnsResolverUnsolicitedEventListener.PREFIX_OPERATION_ADDED) {
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004330 try {
paulhu7c0a2e62021-01-08 00:51:49 +08004331 prefix = new IpPrefix(InetAddresses.parseNumericAddress(prefixAddress),
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004332 prefixLength);
4333 } catch (IllegalArgumentException e) {
paulhu7c0a2e62021-01-08 00:51:49 +08004334 loge("Invalid NAT64 prefix " + prefixAddress + "/" + prefixLength);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004335 return;
4336 }
4337 }
4338
Lorenzo Colittid523d142020-04-01 20:16:30 +09004339 nai.clatd.setNat64PrefixFromDns(prefix);
Lorenzo Colittif7e17392019-01-08 10:04:25 +09004340 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4341 }
4342
Hai Shalome58bdc62021-01-11 18:45:34 -08004343 private void handleCapportApiDataUpdate(@NonNull final NetworkAgentInfo nai,
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004344 @Nullable final CaptivePortalData data) {
Hai Shalome58bdc62021-01-11 18:45:34 -08004345 nai.capportApiData = data;
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09004346 // CaptivePortalData will be merged into LinkProperties from NetworkAgentInfo
4347 handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
4348 }
4349
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004350 /**
junyulai2b6f0c22021-02-03 20:15:30 +08004351 * Updates the inactivity state from the network requests inside the NAI.
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004352 * @param nai the agent info to update
4353 * @param now the timestamp of the event causing this update
junyulai2b6f0c22021-02-03 20:15:30 +08004354 * @return whether the network was inactive as a result of this update
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004355 */
junyulai2b6f0c22021-02-03 20:15:30 +08004356 private boolean updateInactivityState(@NonNull final NetworkAgentInfo nai, final long now) {
4357 // 1. Update the inactivity timer. If it's changed, reschedule or cancel the alarm.
4358 // 2. If the network was inactive and there are now requests, unset inactive.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004359 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
junyulai2b6f0c22021-02-03 20:15:30 +08004360 // one lingered request, set inactive.
4361 nai.updateInactivityTimer();
junyulai0ac374f2020-12-14 18:41:52 +08004362 if (nai.isInactive() && nai.numForegroundNetworkRequests() > 0) {
junyulai2b6f0c22021-02-03 20:15:30 +08004363 if (DBG) log("Unsetting inactive " + nai.toShortString());
4364 nai.unsetInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004365 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
junyulai2b6f0c22021-02-03 20:15:30 +08004366 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getInactivityExpiry() > 0) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004367 if (DBG) {
junyulai2b6f0c22021-02-03 20:15:30 +08004368 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
4369 log("Setting inactive " + nai.toShortString() + " for " + lingerTime + "ms");
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004370 }
junyulai2b6f0c22021-02-03 20:15:30 +08004371 nai.setInactive();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004372 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004373 return true;
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09004374 }
Chalard Jean8fd82ae2019-12-04 18:49:18 +09004375 return false;
Paul Jensend5f53392014-11-25 15:26:53 -05004376 }
4377
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004378 private void handleNetworkAgentRegistered(Message msg) {
4379 final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
4380 if (!mNetworkAgentInfos.contains(nai)) {
4381 return;
4382 }
4383
4384 if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
4385 if (VDBG) log("NetworkAgent registered");
4386 } else {
4387 loge("Error connecting NetworkAgent");
4388 mNetworkAgentInfos.remove(nai);
4389 if (nai != null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09004390 final boolean wasDefault = isDefaultNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004391 synchronized (mNetworkForNetId) {
4392 mNetworkForNetId.remove(nai.network.getNetId());
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004393 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004394 mNetIdManager.releaseNetId(nai.network.getNetId());
4395 // Just in case.
Chalard Jean5b409c72021-02-04 13:12:59 +09004396 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07004397 }
4398 }
4399 }
Paul Jensend5f53392014-11-25 15:26:53 -05004400
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004401 private static boolean shouldDestroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Chalard Jean254bd162022-08-25 13:04:51 +09004402 return nai.isCreated() && !nai.isDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004403 }
4404
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004405 @VisibleForTesting
4406 boolean shouldIgnoreValidationFailureAfterRoam(NetworkAgentInfo nai) {
Lorenzo Colittia63e2342022-03-23 23:17:16 +09004407 // T+ devices should use unregisterAfterReplacement.
he_won.hwang881307a2022-03-15 21:23:52 +09004408 if (SdkLevel.isAtLeastT()) return false;
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004409
4410 // If the network never roamed, return false. The check below is not sufficient if time
4411 // since boot is less than blockTimeOut, though that's extremely unlikely to happen.
4412 if (nai.lastRoamTime == 0) return false;
4413
he_won.hwang881307a2022-03-15 21:23:52 +09004414 final long blockTimeOut = Long.valueOf(mResources.get().getInteger(
4415 R.integer.config_validationFailureAfterRoamIgnoreTimeMillis));
Lorenzo Colitti580d0d52022-10-13 19:56:58 +09004416 if (blockTimeOut <= MAX_VALIDATION_IGNORE_AFTER_ROAM_TIME_MS
he_won.hwang881307a2022-03-15 21:23:52 +09004417 && blockTimeOut >= 0) {
Chalard Jean254bd162022-08-25 13:04:51 +09004418 final long currentTimeMs = SystemClock.elapsedRealtime();
4419 long timeSinceLastRoam = currentTimeMs - nai.lastRoamTime;
he_won.hwang881307a2022-03-15 21:23:52 +09004420 if (timeSinceLastRoam <= blockTimeOut) {
4421 log ("blocked because only " + timeSinceLastRoam + "ms after roam");
4422 return true;
4423 }
4424 }
4425 return false;
4426 }
4427
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004428 private void handleNetworkAgentDisconnected(Message msg) {
4429 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
Tyler Wear614b27b2021-08-19 09:33:26 -07004430 disconnectAndDestroyNetwork(nai);
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004431 }
4432
Chalard Jeand9fffc32018-05-11 20:19:20 +09004433 // Destroys a network, remove references to it from the internal state managed by
4434 // ConnectivityService, free its interfaces and clean up.
4435 // Must be called on the Handler thread.
4436 private void disconnectAndDestroyNetwork(NetworkAgentInfo nai) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004437 ensureRunningOnConnectivityServiceThread();
Tyler Wear614b27b2021-08-19 09:33:26 -07004438
4439 if (!mNetworkAgentInfos.contains(nai)) return;
4440
Chalard Jeand9fffc32018-05-11 20:19:20 +09004441 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09004442 log(nai.toShortString() + " disconnected, was satisfying " + nai.numNetworkRequests());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004443 }
lucaslinb25c9a62019-02-12 15:30:13 +08004444 // Clear all notifications of this network.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004445 mNotifier.clearNotification(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004446 // A network agent has disconnected.
4447 // TODO - if we move the logic to the network agent (have them disconnect
4448 // because they lost all their requests or because their score isn't good)
4449 // then they would disconnect organically, report their new state and then
4450 // disconnect the channel.
4451 if (nai.networkInfo.isConnected()) {
4452 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
4453 null, null);
4454 }
Chalard Jean5b409c72021-02-04 13:12:59 +09004455 final boolean wasDefault = isDefaultNetwork(nai);
4456 if (wasDefault) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004457 mDefaultInetConditionPublished = 0;
Chalard Jeand9fffc32018-05-11 20:19:20 +09004458 }
4459 notifyIfacesChangedForNetworkStats();
4460 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
4461 // by other networks that are already connected. Perhaps that can be done by
4462 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
4463 // of rematchAllNetworksAndRequests
4464 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
junyulai011b1f12019-01-03 18:50:15 +08004465 mKeepaliveTracker.handleStopAllKeepalives(nai, SocketKeepalive.ERROR_INVALID_NETWORK);
Daniel Brightf9e945b2020-06-15 16:10:01 -07004466
4467 mQosCallbackTracker.handleNetworkReleased(nai.network);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004468 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
4469 // Disable wakeup packet monitoring for each interface.
Suprabh Shukla1e312032023-01-24 03:36:37 -08004470 wakeupModifyInterface(iface, nai, false);
Chalard Jeand9fffc32018-05-11 20:19:20 +09004471 }
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09004472 nai.networkMonitor().notifyNetworkDisconnected();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09004473 mNetworkAgentInfos.remove(nai);
Lorenzo Colitti84298d82019-02-19 13:21:56 +09004474 nai.clatd.update();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004475 synchronized (mNetworkForNetId) {
4476 // Remove the NetworkAgent, but don't mark the netId as
4477 // available until we've told netd to delete it below.
Serik Beketayevec8ad212020-12-07 22:43:07 -08004478 mNetworkForNetId.remove(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004479 }
Lorenzo Colitti24c152c2021-01-12 00:34:44 +09004480 propagateUnderlyingNetworkCapabilities(nai.network);
Junyu Lai35665cc2022-12-19 17:37:48 +08004481 // Update allowed network lists in netd. This should be called after removing nai
4482 // from mNetworkAgentInfos.
4483 updateProfileAllowedNetworks();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004484 // Remove all previously satisfied requests.
4485 for (int i = 0; i < nai.numNetworkRequests(); i++) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004486 final NetworkRequest request = nai.requestAt(i);
Chalard Jeandd8adb92019-11-05 15:07:09 +09004487 final NetworkRequestInfo nri = mNetworkRequests.get(request);
James Mattisa076c532020-12-02 14:12:41 -08004488 final NetworkAgentInfo currentNetwork = nri.getSatisfier();
Serik Beketayevec8ad212020-12-07 22:43:07 -08004489 if (currentNetwork != null
4490 && currentNetwork.network.getNetId() == nai.network.getNetId()) {
James Mattisd31bdfa2020-12-23 16:37:26 -08004491 // uid rules for this network will be removed in destroyNativeNetwork(nai).
Chalard Jean0354d8c2021-01-12 10:58:56 +09004492 // TODO : setting the satisfier is in fact the job of the rematch. Teach the
4493 // rematch not to keep disconnected agents instead of setting it here ; this
4494 // will also allow removing updating the offers below.
James Mattisa076c532020-12-02 14:12:41 -08004495 nri.setSatisfier(null, null);
Chalard Jean0354d8c2021-01-12 10:58:56 +09004496 for (final NetworkOfferInfo noi : mNetworkOffers) {
4497 informOffer(nri, noi.offer, mNetworkRanker);
James Mattisd31bdfa2020-12-23 16:37:26 -08004498 }
James Mattise3ef1912020-12-20 11:09:58 -08004499
Chalard Jean5b409c72021-02-04 13:12:59 +09004500 if (mDefaultRequest == nri) {
James Mattise3ef1912020-12-20 11:09:58 -08004501 // TODO : make battery stats aware that since 2013 multiple interfaces may be
Chalard Jean5b409c72021-02-04 13:12:59 +09004502 // active at the same time. For now keep calling this with the default
James Mattise3ef1912020-12-20 11:09:58 -08004503 // network, because while incorrect this is the closest to the old (also
4504 // incorrect) behavior.
4505 mNetworkActivityTracker.updateDataActivityTracking(
4506 null /* newNetwork */, nai);
James Mattise3ef1912020-12-20 11:09:58 -08004507 ensureNetworkTransitionWakelock(nai.toShortString());
4508 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09004509 }
4510 }
junyulai2b6f0c22021-02-03 20:15:30 +08004511 nai.clearInactivityState();
James Mattise3ef1912020-12-20 11:09:58 -08004512 // TODO: mLegacyTypeTracker.remove seems redundant given there's a full rematch right after.
Chalard Jean5b409c72021-02-04 13:12:59 +09004513 // Currently, deleting it breaks tests that check for the default network disconnecting.
James Mattise3ef1912020-12-20 11:09:58 -08004514 // Find out why, fix the rematch code, and delete this.
Chalard Jean5b409c72021-02-04 13:12:59 +09004515 mLegacyTypeTracker.remove(nai, wasDefault);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09004516 rematchAllNetworksAndRequests();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004517 mLingerMonitor.noteDisconnect(nai);
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004518
4519 // Immediate teardown.
4520 if (nai.teardownDelayMs == 0) {
4521 destroyNetwork(nai);
4522 return;
4523 }
4524
4525 // Delayed teardown.
Chalard Jean254bd162022-08-25 13:04:51 +09004526 if (nai.isCreated()) {
Pavan Kumar Mbe994242021-09-29 17:59:24 +05304527 try {
4528 mNetd.networkSetPermissionForNetwork(nai.network.netId, INetd.PERMISSION_SYSTEM);
4529 } catch (RemoteException e) {
4530 Log.d(TAG, "Error marking network restricted during teardown: ", e);
4531 }
Lorenzo Colittid5385c42021-03-11 01:32:09 +09004532 }
4533 mHandler.postDelayed(() -> destroyNetwork(nai), nai.teardownDelayMs);
4534 }
4535
4536 private void destroyNetwork(NetworkAgentInfo nai) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004537 if (shouldDestroyNativeNetwork(nai)) {
Chalard Jeand9fffc32018-05-11 20:19:20 +09004538 // Tell netd to clean up the configuration for this network
4539 // (routing rules, DNS, etc).
4540 // This may be slow as it requires a lot of netd shelling out to ip and
4541 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
Chalard Jean5b409c72021-02-04 13:12:59 +09004542 // after we've rematched networks with requests (which might change the default
4543 // network or service a new request from an app), so network traffic isn't interrupted
4544 // for an unnecessarily long time.
Luke Huangfdd11f82019-04-09 18:41:49 +08004545 destroyNativeNetwork(nai);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004546 }
Chalard Jean254bd162022-08-25 13:04:51 +09004547 if (!nai.isCreated() && !SdkLevel.isAtLeastT()) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004548 // Backwards compatibility: send onNetworkDestroyed even if network was never created.
4549 // This can never run if the code above runs because shouldDestroyNativeNetwork is
4550 // false if the network was never created.
4551 // TODO: delete when S is no longer supported.
4552 nai.onNetworkDestroyed();
Chalard Jeand9fffc32018-05-11 20:19:20 +09004553 }
Serik Beketayevec8ad212020-12-07 22:43:07 -08004554 mNetIdManager.releaseNetId(nai.network.getNetId());
Chalard Jeand9fffc32018-05-11 20:19:20 +09004555 }
4556
Ken Chen6df7a902021-04-09 15:08:42 +08004557 private boolean createNativeNetwork(@NonNull NetworkAgentInfo nai) {
Luke Huangfdd11f82019-04-09 18:41:49 +08004558 try {
4559 // This should never fail. Specifying an already in use NetID will cause failure.
Ken Chen6df7a902021-04-09 15:08:42 +08004560 final NativeNetworkConfig config;
4561 if (nai.isVPN()) {
4562 if (getVpnType(nai) == VpnManager.TYPE_VPN_NONE) {
Ken Chen755a4e72021-05-12 13:38:13 +08004563 Log.wtf(TAG, "Unable to get VPN type from network " + nai.toShortString());
Ken Chen6df7a902021-04-09 15:08:42 +08004564 return false;
4565 }
4566 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.VIRTUAL,
4567 INetd.PERMISSION_NONE,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004568 !nai.networkAgentConfig.allowBypass /* secure */,
Chiachang Wang9164c102022-01-13 10:54:32 +08004569 getVpnType(nai), nai.networkAgentConfig.excludeLocalRouteVpn);
Luke Huangfdd11f82019-04-09 18:41:49 +08004570 } else {
Ken Chen6df7a902021-04-09 15:08:42 +08004571 config = new NativeNetworkConfig(nai.network.getNetId(), NativeNetworkType.PHYSICAL,
Chalard Jean46bfbf02022-02-02 00:56:25 +09004572 getNetworkPermission(nai.networkCapabilities),
4573 false /* secure */,
4574 VpnManager.TYPE_VPN_NONE,
4575 false /* excludeLocalRoutes */);
Luke Huangfdd11f82019-04-09 18:41:49 +08004576 }
Ken Chen6df7a902021-04-09 15:08:42 +08004577 mNetd.networkCreate(config);
4578 mDnsResolver.createNetworkCache(nai.network.getNetId());
4579 mDnsManager.updateTransportsForNetwork(nai.network.getNetId(),
4580 nai.networkCapabilities.getTransportTypes());
Luke Huangfdd11f82019-04-09 18:41:49 +08004581 return true;
4582 } catch (RemoteException | ServiceSpecificException e) {
Ken Chen755a4e72021-05-12 13:38:13 +08004583 loge("Error creating network " + nai.toShortString() + ": " + e.getMessage());
Luke Huangfdd11f82019-04-09 18:41:49 +08004584 return false;
4585 }
4586 }
4587
Ken Chen6df7a902021-04-09 15:08:42 +08004588 private void destroyNativeNetwork(@NonNull NetworkAgentInfo nai) {
Tyler Wear3ad80892022-02-03 15:14:44 -08004589 if (mDscpPolicyTracker != null) {
4590 mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
4591 }
Luke Huangfdd11f82019-04-09 18:41:49 +08004592 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004593 mNetd.networkDestroy(nai.network.getNetId());
Wangkeun Ohe0a9d1b2021-01-20 11:04:46 +09004594 } catch (RemoteException | ServiceSpecificException e) {
4595 loge("Exception destroying network(networkDestroy): " + e);
4596 }
4597 try {
Ken Chen6df7a902021-04-09 15:08:42 +08004598 mDnsResolver.destroyNetworkCache(nai.network.getNetId());
Luke Huangfdd11f82019-04-09 18:41:49 +08004599 } catch (RemoteException | ServiceSpecificException e) {
4600 loge("Exception destroying network: " + e);
4601 }
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004602 // TODO: defer calling this until the network is removed from mNetworkAgentInfos.
4603 // Otherwise, a private DNS configuration update for a destroyed network, or one that never
4604 // gets created, could add data to DnsManager data structures that will never get deleted.
4605 mDnsManager.removeNetwork(nai.network);
4606
4607 // clean up tc police filters on interface.
Chalard Jean254bd162022-08-25 13:04:51 +09004608 if (nai.everConnected() && canNetworkBeRateLimited(nai) && mIngressRateLimit >= 0) {
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004609 mDeps.disableIngressRateLimit(nai.linkProperties.getInterfaceName());
4610 }
4611
Chalard Jean254bd162022-08-25 13:04:51 +09004612 nai.setDestroyed();
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09004613 nai.onNetworkDestroyed();
Luke Huangfdd11f82019-04-09 18:41:49 +08004614 }
4615
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004616 // If this method proves to be too slow then we can maintain a separate
4617 // pendingIntent => NetworkRequestInfo map.
4618 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
4619 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004620 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
4621 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
4622 if (existingPendingIntent != null &&
Remi NGUYEN VAN18a979f2021-06-04 18:51:25 +09004623 mDeps.intentFilterEquals(existingPendingIntent, pendingIntent)) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004624 return entry.getValue();
4625 }
4626 }
4627 return null;
4628 }
4629
Chalard Jean524f0b12021-10-25 21:11:56 +09004630 private void checkNrisConsistency(final NetworkRequestInfo nri) {
4631 if (SdkLevel.isAtLeastT()) {
4632 for (final NetworkRequestInfo n : mNetworkRequests.values()) {
4633 if (n.mBinder != null && n.mBinder == nri.mBinder) {
4634 // Temporary help to debug b/194394697 ; TODO : remove this function when the
4635 // bug is fixed.
4636 dumpAllRequestInfoLogsToLogcat();
Chalard Jeanba551d42021-10-28 12:45:12 +09004637 throw new IllegalStateException("This NRI is already registered. New : " + nri
4638 + ", existing : " + n);
Chalard Jean524f0b12021-10-25 21:11:56 +09004639 }
4640 }
4641 }
4642 }
4643
Chalard Jeanac9ace02022-01-26 16:54:05 +09004644 private boolean hasCarrierPrivilegeForNetworkCaps(final int callingUid,
4645 @NonNull final NetworkCapabilities caps) {
junyulai96bd9fe2022-03-08 17:36:42 +08004646 if (mCarrierPrivilegeAuthenticator != null) {
Chalard Jeanac9ace02022-01-26 16:54:05 +09004647 return mCarrierPrivilegeAuthenticator.hasCarrierPrivilegeForNetworkCapabilities(
4648 callingUid, caps);
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004649 }
4650 return false;
4651 }
4652
James Mattisf7027322020-12-13 16:28:14 -08004653 private void handleRegisterNetworkRequestWithIntent(@NonNull final Message msg) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004654 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
James Mattisf7027322020-12-13 16:28:14 -08004655 // handleRegisterNetworkRequestWithIntent() doesn't apply to multilayer requests.
4656 ensureNotMultilayerRequest(nri, "handleRegisterNetworkRequestWithIntent");
4657 final NetworkRequestInfo existingRequest =
4658 findExistingNetworkRequestInfo(nri.mPendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004659 if (existingRequest != null) { // remove the existing request.
James Mattisf7027322020-12-13 16:28:14 -08004660 if (DBG) {
4661 log("Replacing " + existingRequest.mRequests.get(0) + " with "
4662 + nri.mRequests.get(0) + " because their intents matched.");
4663 }
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09004664 handleReleaseNetworkRequest(existingRequest.mRequests.get(0), mDeps.getCallingUid(),
Etan Cohenfbfdd842019-01-08 12:09:18 -08004665 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004666 }
Erik Kline05f2b402015-04-30 12:58:40 +09004667 handleRegisterNetworkRequest(nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004668 }
4669
James Mattisf7027322020-12-13 16:28:14 -08004670 private void handleRegisterNetworkRequest(@NonNull final NetworkRequestInfo nri) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004671 handleRegisterNetworkRequests(Collections.singleton(nri));
James Mattis45d81842021-01-10 14:24:24 -08004672 }
4673
James Mattis3ce3d3c2021-02-09 18:18:28 -08004674 private void handleRegisterNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004675 ensureRunningOnConnectivityServiceThread();
James Mattis45d81842021-01-10 14:24:24 -08004676 for (final NetworkRequestInfo nri : nris) {
4677 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004678 checkNrisConsistency(nri);
James Mattis45d81842021-01-10 14:24:24 -08004679 for (final NetworkRequest req : nri.mRequests) {
4680 mNetworkRequests.put(req, nri);
junyulai1b1c8742021-03-12 20:05:08 +08004681 // TODO: Consider update signal strength for other types.
James Mattis45d81842021-01-10 14:24:24 -08004682 if (req.isListen()) {
4683 for (final NetworkAgentInfo network : mNetworkAgentInfos) {
4684 if (req.networkCapabilities.hasSignalStrength()
4685 && network.satisfiesImmutableCapabilitiesOf(req)) {
4686 updateSignalStrengthThresholds(network, "REGISTER", req);
4687 }
James Mattisf7027322020-12-13 16:28:14 -08004688 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004689 }
4690 }
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08004691
Chalard Jeanb5becbc2021-03-05 19:18:14 +09004692 // If this NRI has a satisfier already, it is replacing an older request that
4693 // has been removed. Track it.
4694 final NetworkRequest activeRequest = nri.getActiveRequest();
4695 if (null != activeRequest) {
4696 // If there is an active request, then for sure there is a satisfier.
4697 nri.getSatisfier().addRequest(activeRequest);
4698 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09004699 }
James Mattisf7027322020-12-13 16:28:14 -08004700
Remi NGUYEN VAN959d2cb2021-08-02 13:04:31 +09004701 if (mFlags.noRematchAllRequestsOnRegister()) {
4702 rematchNetworksAndRequests(nris);
4703 } else {
4704 rematchAllNetworksAndRequests();
4705 }
James Mattis45d81842021-01-10 14:24:24 -08004706
Chalard Jean0354d8c2021-01-12 10:58:56 +09004707 // Requests that have not been matched to a network will not have been sent to the
4708 // providers, because the old satisfier and the new satisfier are the same (null in this
4709 // case). Send these requests to the providers.
4710 for (final NetworkRequestInfo nri : nris) {
4711 for (final NetworkOfferInfo noi : mNetworkOffers) {
4712 informOffer(nri, noi.offer, mNetworkRanker);
James Mattis45d81842021-01-10 14:24:24 -08004713 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004714 }
4715 }
4716
James Mattisf7027322020-12-13 16:28:14 -08004717 private void handleReleaseNetworkRequestWithIntent(@NonNull final PendingIntent pendingIntent,
4718 final int callingUid) {
4719 final NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004720 if (nri != null) {
James Mattisf7027322020-12-13 16:28:14 -08004721 // handleReleaseNetworkRequestWithIntent() paths don't apply to multilayer requests.
4722 ensureNotMultilayerRequest(nri, "handleReleaseNetworkRequestWithIntent");
4723 handleReleaseNetworkRequest(
4724 nri.mRequests.get(0),
4725 callingUid,
4726 /* callOnUnavailable */ false);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08004727 }
4728 }
4729
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004730 // Determines whether the network is the best (or could become the best, if it validated), for
4731 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
4732 // on the value of reason:
4733 //
4734 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
4735 // then it should be torn down.
4736 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
4737 // then it should be lingered.
4738 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004739 ensureRunningOnConnectivityServiceThread();
Chalard Jean947acd42021-03-08 22:29:27 +09004740
Chalard Jean254bd162022-08-25 13:04:51 +09004741 if (!nai.everConnected() || nai.isVPN() || nai.isInactive()
Chalard Jean947acd42021-03-08 22:29:27 +09004742 || nai.getScore().getKeepConnectedReason() != NetworkScore.KEEP_CONNECTED_NONE) {
4743 return false;
4744 }
4745
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004746 final int numRequests;
4747 switch (reason) {
4748 case TEARDOWN:
4749 numRequests = nai.numRequestNetworkRequests();
4750 break;
4751 case LINGER:
4752 numRequests = nai.numForegroundNetworkRequests();
4753 break;
4754 default:
Aaron Huang6616df32020-10-30 22:04:25 +08004755 Log.wtf(TAG, "Invalid reason. Cannot happen.");
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004756 return true;
4757 }
4758
Chalard Jean947acd42021-03-08 22:29:27 +09004759 if (numRequests > 0) return false;
4760
Paul Jensende49eb12015-06-25 15:30:08 -04004761 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
James Mattis3d229892020-11-16 16:46:28 -08004762 if (reason == UnneededFor.LINGER
4763 && !nri.isMultilayerRequest()
4764 && nri.mRequests.get(0).isBackgroundRequest()) {
Lorenzo Colitti2666be82016-09-09 18:48:56 +09004765 // Background requests don't affect lingering.
4766 continue;
4767 }
4768
James Mattis3d229892020-11-16 16:46:28 -08004769 if (isNetworkPotentialSatisfier(nai, nri)) {
Paul Jensende49eb12015-06-25 15:30:08 -04004770 return false;
Paul Jensen9e078d22014-12-09 11:43:45 -05004771 }
4772 }
Paul Jensende49eb12015-06-25 15:30:08 -04004773 return true;
Paul Jensen9e078d22014-12-09 11:43:45 -05004774 }
4775
James Mattis3d229892020-11-16 16:46:28 -08004776 private boolean isNetworkPotentialSatisfier(
4777 @NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
4778 // listen requests won't keep up a network satisfying it. If this is not a multilayer
James Mattis64b8b0f2020-11-24 17:40:49 -08004779 // request, return immediately. For multilayer requests, check to see if any of the
4780 // multilayer requests may have a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004781 if (!nri.isMultilayerRequest() && (nri.mRequests.get(0).isListen()
4782 || nri.mRequests.get(0).isListenForBest())) {
James Mattis3d229892020-11-16 16:46:28 -08004783 return false;
4784 }
4785 for (final NetworkRequest req : nri.mRequests) {
James Mattisa076c532020-12-02 14:12:41 -08004786 // This multilayer listen request is satisfied therefore no further requests need to be
4787 // evaluated deeming this network not a potential satisfier.
junyulai1b1c8742021-03-12 20:05:08 +08004788 if ((req.isListen() || req.isListenForBest()) && nri.getActiveRequest() == req) {
James Mattisa076c532020-12-02 14:12:41 -08004789 return false;
4790 }
James Mattis3d229892020-11-16 16:46:28 -08004791 // As non-multilayer listen requests have already returned, the below would only happen
4792 // for a multilayer request therefore continue to the next request if available.
junyulai1b1c8742021-03-12 20:05:08 +08004793 if (req.isListen() || req.isListenForBest()) {
James Mattis3d229892020-11-16 16:46:28 -08004794 continue;
4795 }
Chalard Jean2a96cf22022-09-06 13:44:10 +09004796 // If this Network is already the best Network for a request, or if
James Mattis3d229892020-11-16 16:46:28 -08004797 // there is hope for it to become one if it validated, then it is needed.
4798 if (candidate.satisfies(req)) {
4799 // As soon as a network is found that satisfies a request, return. Specifically for
4800 // multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
4801 // is important so as to not evaluate lower priority requests further in
4802 // nri.mRequests.
Chalard Jeanc81d4c32021-04-07 17:06:19 +09004803 final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
4804 ? nri.getSatisfier() : null;
4805 // Note that this catches two important cases:
4806 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
4807 // is currently satisfying the request. This is desirable when
4808 // cellular ends up validating but WiFi does not.
4809 // 2. Unvalidated WiFi will not be reaped when validated cellular
4810 // is currently satisfying the request. This is desirable when
4811 // WiFi ends up validating and out scoring cellular.
4812 return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
James Mattis3d229892020-11-16 16:46:28 -08004813 }
4814 }
4815
4816 return false;
4817 }
4818
Erik Kline0c04b742016-07-07 16:50:58 +09004819 private NetworkRequestInfo getNriForAppRequest(
4820 NetworkRequest request, int callingUid, String requestedOperation) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08004821 // Looking up the app passed param request in mRequests isn't possible since it may return
4822 // null for a request managed by a per-app default. Therefore use getNriForAppRequest() to
4823 // do the lookup since that will also find per-app default managed requests.
James Mattisd7647592021-02-17 16:13:05 -08004824 // Additionally, this lookup needs to be relatively fast (hence the lookup optimization)
4825 // to avoid potential race conditions when validating a package->uid mapping when sending
4826 // the callback on the very low-chance that an application shuts down prior to the callback
4827 // being sent.
4828 final NetworkRequestInfo nri = mNetworkRequests.get(request) != null
4829 ? mNetworkRequests.get(request) : getNriForAppRequest(request);
Erik Kline0c04b742016-07-07 16:50:58 +09004830
Robert Greenwaltf99b8392014-03-26 16:47:06 -07004831 if (nri != null) {
lucaslin5aad7852021-03-15 15:35:38 +08004832 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Kline0c04b742016-07-07 16:50:58 +09004833 log(String.format("UID %d attempted to %s for unowned request %s",
4834 callingUid, requestedOperation, nri));
4835 return null;
Paul Jensen961cb0d2014-05-16 14:31:12 -04004836 }
Erik Kline0c04b742016-07-07 16:50:58 +09004837 }
4838
4839 return nri;
4840 }
4841
James Mattisf7027322020-12-13 16:28:14 -08004842 private void ensureNotMultilayerRequest(@NonNull final NetworkRequestInfo nri,
4843 final String callingMethod) {
4844 if (nri.isMultilayerRequest()) {
4845 throw new IllegalStateException(
4846 callingMethod + " does not support multilayer requests.");
Erik Kline155a59a2015-11-25 12:49:38 +09004847 }
4848 }
4849
James Mattisf7027322020-12-13 16:28:14 -08004850 private void handleTimedOutNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Erik Kline0c04b742016-07-07 16:50:58 +09004851 ensureRunningOnConnectivityServiceThread();
James Mattisf7027322020-12-13 16:28:14 -08004852 // handleTimedOutNetworkRequest() is part of the requestNetwork() flow which works off of a
4853 // single NetworkRequest and thus does not apply to multilayer requests.
4854 ensureNotMultilayerRequest(nri, "handleTimedOutNetworkRequest");
4855 if (mNetworkRequests.get(nri.mRequests.get(0)) == null) {
Erik Kline0c04b742016-07-07 16:50:58 +09004856 return;
4857 }
James Mattis2516da32021-01-31 17:06:19 -08004858 if (nri.isBeingSatisfied()) {
Erik Kline0c04b742016-07-07 16:50:58 +09004859 return;
4860 }
James Mattisf7027322020-12-13 16:28:14 -08004861 if (VDBG || (DBG && nri.mRequests.get(0).isRequest())) {
4862 log("releasing " + nri.mRequests.get(0) + " (timeout)");
Erik Kline0c04b742016-07-07 16:50:58 +09004863 }
4864 handleRemoveNetworkRequest(nri);
James Mattisf7027322020-12-13 16:28:14 -08004865 callCallbackForRequest(
4866 nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline0c04b742016-07-07 16:50:58 +09004867 }
4868
James Mattisf7027322020-12-13 16:28:14 -08004869 private void handleReleaseNetworkRequest(@NonNull final NetworkRequest request,
4870 final int callingUid,
4871 final boolean callOnUnavailable) {
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004872 final NetworkRequestInfo nri =
4873 getNriForAppRequest(request, callingUid, "release NetworkRequest");
4874 if (nri == null) {
4875 return;
Erik Kline155a59a2015-11-25 12:49:38 +09004876 }
James Mattisf7027322020-12-13 16:28:14 -08004877 if (VDBG || (DBG && request.isRequest())) {
4878 log("releasing " + request + " (release request)");
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09004879 }
4880 handleRemoveNetworkRequest(nri);
Etan Cohenfbfdd842019-01-08 12:09:18 -08004881 if (callOnUnavailable) {
4882 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
4883 }
Erik Kline155a59a2015-11-25 12:49:38 +09004884 }
Erik Kline0c04b742016-07-07 16:50:58 +09004885
James Mattisa076c532020-12-02 14:12:41 -08004886 private void handleRemoveNetworkRequest(@NonNull final NetworkRequestInfo nri) {
Chalard Jean2c8b3e32019-11-05 14:40:23 +09004887 ensureRunningOnConnectivityServiceThread();
James Mattisa076c532020-12-02 14:12:41 -08004888 for (final NetworkRequest req : nri.mRequests) {
James Mattis8f036802021-06-20 16:26:01 -07004889 if (null == mNetworkRequests.remove(req)) {
4890 logw("Attempted removal of untracked request " + req + " for nri " + nri);
4891 continue;
4892 }
James Mattisa076c532020-12-02 14:12:41 -08004893 if (req.isListen()) {
4894 removeListenRequestFromNetworks(req);
4895 }
4896 }
James Mattis8f036802021-06-20 16:26:01 -07004897 nri.unlinkDeathRecipient();
Chalard Jean738c5bf2021-03-01 22:08:57 +09004898 if (mDefaultNetworkRequests.remove(nri)) {
4899 // If this request was one of the defaults, then the UID rules need to be updated
4900 // WARNING : if the app(s) for which this network request is the default are doing
4901 // traffic, this will kill their connected sockets, even if an equivalent request
4902 // is going to be reinstated right away ; unconnected traffic will go on the default
4903 // until the new default is set, which will happen very soon.
4904 // TODO : The only way out of this is to diff old defaults and new defaults, and only
4905 // remove ranges for those requests that won't have a replacement
4906 final NetworkAgentInfo satisfier = nri.getSatisfier();
4907 if (null != satisfier) {
4908 try {
paulhu0e79d952021-06-09 16:11:35 +08004909 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
4910 satisfier.network.getNetId(),
4911 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08004912 nri.getPreferenceOrderForNetd()));
Chalard Jean738c5bf2021-03-01 22:08:57 +09004913 } catch (RemoteException e) {
4914 loge("Exception setting network preference default network", e);
4915 }
4916 }
4917 }
Junyu Lai35665cc2022-12-19 17:37:48 +08004918
Junyu Lai00d92df2022-07-05 11:01:52 +08004919 nri.mPerUidCounter.decrementCount(nri.mUid);
Erik Kline0c04b742016-07-07 16:50:58 +09004920 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Chalard Jean524f0b12021-10-25 21:11:56 +09004921 checkNrisConsistency(nri);
James Mattisa076c532020-12-02 14:12:41 -08004922
4923 if (null != nri.getActiveRequest()) {
Lorenzo Colitti96742d92021-01-29 20:18:03 +09004924 if (!nri.getActiveRequest().isListen()) {
James Mattisa076c532020-12-02 14:12:41 -08004925 removeSatisfiedNetworkRequestFromNetwork(nri);
James Mattisa076c532020-12-02 14:12:41 -08004926 }
4927 }
4928
Chalard Jean0354d8c2021-01-12 10:58:56 +09004929 // For all outstanding offers, cancel any of the layers of this NRI that used to be
4930 // needed for this offer.
4931 for (final NetworkOfferInfo noi : mNetworkOffers) {
4932 for (final NetworkRequest req : nri.mRequests) {
4933 if (req.isRequest() && noi.offer.neededFor(req)) {
4934 noi.offer.onNetworkUnneeded(req);
4935 }
4936 }
4937 }
James Mattisa076c532020-12-02 14:12:41 -08004938 }
4939
James Mattis3ce3d3c2021-02-09 18:18:28 -08004940 private void handleRemoveNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
4941 for (final NetworkRequestInfo nri : nris) {
4942 if (mDefaultRequest == nri) {
4943 // Make sure we never remove the default request.
4944 continue;
4945 }
4946 handleRemoveNetworkRequest(nri);
4947 }
4948 }
4949
James Mattisa076c532020-12-02 14:12:41 -08004950 private void removeListenRequestFromNetworks(@NonNull final NetworkRequest req) {
4951 // listens don't have a singular affected Network. Check all networks to see
4952 // if this listen request applies and remove it.
4953 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
4954 nai.removeRequest(req.requestId);
4955 if (req.networkCapabilities.hasSignalStrength()
4956 && nai.satisfiesImmutableCapabilitiesOf(req)) {
4957 updateSignalStrengthThresholds(nai, "RELEASE", req);
4958 }
4959 }
4960 }
4961
4962 /**
4963 * Remove a NetworkRequestInfo's satisfied request from its 'satisfier' (NetworkAgentInfo) and
4964 * manage the necessary upkeep (linger, teardown networks, etc.) when doing so.
4965 * @param nri the NetworkRequestInfo to disassociate from its current NetworkAgentInfo
4966 */
4967 private void removeSatisfiedNetworkRequestFromNetwork(@NonNull final NetworkRequestInfo nri) {
4968 boolean wasKept = false;
4969 final NetworkAgentInfo nai = nri.getSatisfier();
4970 if (nai != null) {
4971 final int requestLegacyType = nri.getActiveRequest().legacyType;
4972 final boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
4973 nai.removeRequest(nri.getActiveRequest().requestId);
4974 if (VDBG || DDBG) {
4975 log(" Removing from current network " + nai.toShortString()
4976 + ", leaving " + nai.numNetworkRequests() + " requests.");
4977 }
4978 // If there are still lingered requests on this network, don't tear it down,
4979 // but resume lingering instead.
4980 final long now = SystemClock.elapsedRealtime();
junyulai2b6f0c22021-02-03 20:15:30 +08004981 if (updateInactivityState(nai, now)) {
James Mattisa076c532020-12-02 14:12:41 -08004982 notifyNetworkLosing(nai, now);
4983 }
4984 if (unneeded(nai, UnneededFor.TEARDOWN)) {
4985 if (DBG) log("no live requests for " + nai.toShortString() + "; disconnecting");
4986 teardownUnneededNetwork(nai);
4987 } else {
4988 wasKept = true;
4989 }
James Mattisa076c532020-12-02 14:12:41 -08004990 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
4991 // Went from foreground to background.
4992 updateCapabilitiesForNetwork(nai);
Erik Kline0c04b742016-07-07 16:50:58 +09004993 }
4994
Erik Kline0c04b742016-07-07 16:50:58 +09004995 // Maintain the illusion. When this request arrived, we might have pretended
4996 // that a network connected to serve it, even though the network was already
4997 // connected. Now that this request has gone away, we might have to pretend
4998 // that the network disconnected. LegacyTypeTracker will generate that
4999 // phantom disconnect for this type.
James Mattisa076c532020-12-02 14:12:41 -08005000 if (requestLegacyType != TYPE_NONE) {
Erik Kline0c04b742016-07-07 16:50:58 +09005001 boolean doRemove = true;
5002 if (wasKept) {
5003 // check if any of the remaining requests for this network are for the
5004 // same legacy type - if so, don't remove the nai
5005 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5006 NetworkRequest otherRequest = nai.requestAt(i);
James Mattisa076c532020-12-02 14:12:41 -08005007 if (otherRequest.legacyType == requestLegacyType
5008 && otherRequest.isRequest()) {
Erik Kline0c04b742016-07-07 16:50:58 +09005009 if (DBG) log(" still have other legacy request - leaving");
5010 doRemove = false;
Robert Greenwalte8a91242015-01-08 14:43:31 -08005011 }
5012 }
Robert Greenwalt8c5842c2014-08-24 22:52:10 -07005013 }
5014
Erik Kline0c04b742016-07-07 16:50:58 +09005015 if (doRemove) {
James Mattisa076c532020-12-02 14:12:41 -08005016 mLegacyTypeTracker.remove(requestLegacyType, nai, false);
Erik Kline0c04b742016-07-07 16:50:58 +09005017 }
5018 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005019 }
5020 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005021
Junyu Lai00d92df2022-07-05 11:01:52 +08005022 private RequestInfoPerUidCounter getRequestCounter(NetworkRequestInfo nri) {
Junyu Lai4c6fe232023-04-11 11:33:46 +08005023 return checkAnyPermissionOf(mContext,
Lorenzo Colitti6dba5882021-03-30 19:29:00 +09005024 nri.mPid, nri.mUid, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
5025 ? mSystemNetworkRequestCounter : mNetworkRequestCounter;
5026 }
5027
Lorenzo Colittid6459092016-07-04 12:55:44 +09005028 @Override
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005029 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
lucaslin2240ef62019-03-12 13:08:03 +08005030 enforceNetworkStackSettingsOrSetup();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005031 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichif4210292017-04-21 15:07:12 +09005032 encodeBool(accept), encodeBool(always), network));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005033 }
5034
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005035 @Override
lucaslin2240ef62019-03-12 13:08:03 +08005036 public void setAcceptPartialConnectivity(Network network, boolean accept, boolean always) {
5037 enforceNetworkStackSettingsOrSetup();
5038 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY,
5039 encodeBool(accept), encodeBool(always), network));
5040 }
5041
5042 @Override
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005043 public void setAvoidUnvalidated(Network network) {
lucaslin2240ef62019-03-12 13:08:03 +08005044 enforceNetworkStackSettingsOrSetup();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005045 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
5046 }
5047
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005048 @Override
5049 public void setTestAllowBadWifiUntil(long timeMs) {
5050 enforceSettingsPermission();
5051 if (!Build.isDebuggable()) {
5052 throw new IllegalStateException("Does not support in non-debuggable build");
5053 }
5054
5055 if (timeMs > System.currentTimeMillis() + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS) {
5056 throw new IllegalArgumentException("It should not exceed "
5057 + MAX_TEST_ALLOW_BAD_WIFI_UNTIL_MS + "ms from now");
5058 }
5059
5060 mHandler.sendMessage(
5061 mHandler.obtainMessage(EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL, timeMs));
5062 }
5063
chiachangwange0192a72023-02-06 13:25:01 +00005064 @Override
5065 public void setTestLowTcpPollingTimerForKeepalive(long timeMs) {
5066 enforceSettingsPermission();
chiachangwange0192a72023-02-06 13:25:01 +00005067
5068 if (timeMs > System.currentTimeMillis() + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS) {
5069 throw new IllegalArgumentException("Argument should not exceed "
5070 + MAX_TEST_LOW_TCP_POLLING_UNTIL_MS + "ms from now");
5071 }
5072
5073 mHandler.sendMessage(
5074 mHandler.obtainMessage(EVENT_SET_LOW_TCP_POLLING_UNTIL, timeMs));
5075 }
5076
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005077 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
5078 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
5079 " accept=" + accept + " always=" + always);
5080
5081 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5082 if (nai == null) {
5083 // Nothing to do.
5084 return;
5085 }
5086
Chalard Jean254bd162022-08-25 13:04:51 +09005087 if (nai.everValidated()) {
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005088 // The network validated while the dialog box was up. Take no action.
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005089 return;
5090 }
5091
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005092 if (!nai.networkAgentConfig.explicitlySelected) {
Aaron Huang6616df32020-10-30 22:04:25 +08005093 Log.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005094 }
5095
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005096 if (accept != nai.networkAgentConfig.acceptUnvalidated) {
5097 nai.networkAgentConfig.acceptUnvalidated = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005098 // If network becomes partial connectivity and user already accepted to use this
5099 // network, we should respect the user's option and don't need to popup the
5100 // PARTIAL_CONNECTIVITY notification to user again.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005101 nai.networkAgentConfig.acceptPartialConnectivity = accept;
Chalard Jean142f0fe2021-03-31 23:19:05 +09005102 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005103 rematchAllNetworksAndRequests();
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005104 }
5105
5106 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005107 nai.onSaveAcceptUnvalidated(accept);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005108 }
5109
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005110 if (!accept) {
Paul Jensen57e65702015-07-13 15:19:51 -04005111 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005112 nai.onPreventAutomaticReconnect();
Chalard Jean9dd11612018-06-04 16:52:49 +09005113 // Teardown the network.
Paul Jensen57e65702015-07-13 15:19:51 -04005114 teardownUnneededNetwork(nai);
Lorenzo Colitti74baf412015-05-21 16:17:05 +09005115 }
5116
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005117 }
5118
lucaslin2240ef62019-03-12 13:08:03 +08005119 private void handleSetAcceptPartialConnectivity(Network network, boolean accept,
5120 boolean always) {
5121 if (DBG) {
5122 log("handleSetAcceptPartialConnectivity network=" + network + " accept=" + accept
5123 + " always=" + always);
5124 }
5125
5126 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5127 if (nai == null) {
5128 // Nothing to do.
5129 return;
5130 }
5131
Chalard Jean254bd162022-08-25 13:04:51 +09005132 if (nai.isValidated()) {
lucaslin2240ef62019-03-12 13:08:03 +08005133 // The network validated while the dialog box was up. Take no action.
5134 return;
5135 }
5136
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005137 if (accept != nai.networkAgentConfig.acceptPartialConnectivity) {
5138 nai.networkAgentConfig.acceptPartialConnectivity = accept;
lucaslin2240ef62019-03-12 13:08:03 +08005139 }
5140
5141 // TODO: Use the current design or save the user choice into IpMemoryStore.
5142 if (always) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005143 nai.onSaveAcceptUnvalidated(accept);
lucaslin2240ef62019-03-12 13:08:03 +08005144 }
5145
5146 if (!accept) {
5147 // Tell the NetworkAgent to not automatically reconnect to the network.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005148 nai.onPreventAutomaticReconnect();
lucaslin2240ef62019-03-12 13:08:03 +08005149 // Tear down the network.
5150 teardownUnneededNetwork(nai);
5151 } else {
lucaslinf9bff5b2019-03-20 18:21:59 +08005152 // Inform NetworkMonitor that partial connectivity is acceptable. This will likely
5153 // result in a partial connectivity result which will be processed by
5154 // maybeHandleNetworkMonitorMessage.
Chiachang Wangeff18972019-05-23 16:29:30 +08005155 //
5156 // TODO: NetworkMonitor does not refer to the "never ask again" bit. The bit is stored
5157 // per network. Therefore, NetworkMonitor may still do https probe.
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005158 nai.networkMonitor().setAcceptPartialConnectivity();
lucaslin2240ef62019-03-12 13:08:03 +08005159 }
5160 }
5161
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005162 private void handleSetAvoidUnvalidated(Network network) {
5163 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Chalard Jean254bd162022-08-25 13:04:51 +09005164 if (nai == null || nai.isValidated()) {
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005165 // Nothing to do. The network either disconnected or revalidated.
5166 return;
5167 }
Chalard Jean254bd162022-08-25 13:04:51 +09005168 if (0L == nai.getAvoidUnvalidated()) {
5169 nai.setAvoidUnvalidated();
Chalard Jean142f0fe2021-03-31 23:19:05 +09005170 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005171 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005172 }
5173 }
5174
Chalard Jean5fb43c72022-09-08 19:03:14 +09005175 /** Schedule evaluation timeout */
Chalard Jean4c463082022-09-08 20:52:25 +09005176 @VisibleForTesting
Chalard Jean5fb43c72022-09-08 19:03:14 +09005177 public void scheduleEvaluationTimeout(@NonNull final Network network, final long delayMs) {
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005178 mHandler.sendMessageDelayed(
Chalard Jean5fb43c72022-09-08 19:03:14 +09005179 mHandler.obtainMessage(EVENT_INITIAL_EVALUATION_TIMEOUT, network), delayMs);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005180 }
5181
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005182 @Override
5183 public void startCaptivePortalApp(Network network) {
paulhu8e96a752019-08-12 16:25:11 +08005184 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005185 mHandler.post(() -> {
5186 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5187 if (nai == null) return;
5188 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005189 nai.networkMonitor().launchCaptivePortalApp();
Lorenzo Colitti500dbae2017-04-27 14:30:21 +09005190 });
5191 }
5192
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005193 /**
5194 * NetworkStack endpoint to start the captive portal app. The NetworkStack needs to use this
5195 * endpoint as it does not have INTERACT_ACROSS_USERS_FULL itself.
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005196 * @param network Network on which the captive portal was detected.
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005197 * @param appExtras Bundle to use as intent extras for the captive portal application.
5198 * Must be treated as opaque to avoid preventing the captive portal app to
5199 * update its arguments.
5200 */
5201 @Override
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005202 public void startCaptivePortalAppInternal(Network network, Bundle appExtras) {
paulhude3a2452019-05-14 14:17:44 +08005203 mContext.enforceCallingOrSelfPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
5204 "ConnectivityService");
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005205
5206 final Intent appIntent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
5207 appIntent.putExtras(appExtras);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005208 appIntent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
5209 new CaptivePortal(new CaptivePortalImpl(network).asBinder()));
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005210 appIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
5211
lucaslin75ff7022020-12-17 04:14:35 +08005212 final long token = Binder.clearCallingIdentity();
5213 try {
5214 mContext.startActivityAsUser(appIntent, UserHandle.CURRENT);
5215 } finally {
5216 Binder.restoreCallingIdentity(token);
5217 }
Remi NGUYEN VAN94ff95b2019-02-04 11:32:20 +09005218 }
5219
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005220 private class CaptivePortalImpl extends ICaptivePortal.Stub {
5221 private final Network mNetwork;
5222
5223 private CaptivePortalImpl(Network network) {
5224 mNetwork = network;
5225 }
5226
5227 @Override
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005228 public void appResponse(final int response) {
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005229 if (response == CaptivePortal.APP_RETURN_WANTED_AS_IS) {
5230 enforceSettingsPermission();
Hansen Kurli55396972022-10-28 03:31:17 +00005231 } else if (response == CaptivePortal.APP_RETURN_UNWANTED) {
5232 mHandler.sendMessage(mHandler.obtainMessage(EVENT_USER_DOES_NOT_WANT, mNetwork));
5233 // Since the network will be disconnected, skip notifying NetworkMonitor
5234 return;
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005235 }
5236
Chiachang Wang938bfba2020-01-09 13:50:55 +08005237 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005238 if (nm == null) return;
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005239 nm.notifyCaptivePortalAppFinished(response);
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005240 }
5241
5242 @Override
Chiachang Wang938bfba2020-01-09 13:50:55 +08005243 public void appRequest(final int request) {
5244 final NetworkMonitorManager nm = getNetworkMonitorManager(mNetwork);
5245 if (nm == null) return;
5246
5247 if (request == CaptivePortal.APP_REQUEST_REEVALUATION_REQUIRED) {
Chiachang Wangf7a0f122020-02-12 13:44:50 +08005248 checkNetworkStackPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005249 nm.forceReevaluation(mDeps.getCallingUid());
Chiachang Wang938bfba2020-01-09 13:50:55 +08005250 }
5251 }
5252
5253 @Nullable
5254 private NetworkMonitorManager getNetworkMonitorManager(final Network network) {
5255 // getNetworkAgentInfoForNetwork is thread-safe
5256 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5257 if (nai == null) return null;
5258
5259 // nai.networkMonitor() is thread-safe
5260 return nai.networkMonitor();
5261 }
Remi NGUYEN VANeab0f542019-02-13 20:58:59 +09005262 }
5263
Hugo Benichic9048bc2016-09-14 23:23:08 +00005264 public boolean avoidBadWifi() {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005265 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti21924542016-09-16 23:43:38 +09005266 }
5267
Chalard Jean020b93a2022-09-01 13:20:14 +09005268 private boolean activelyPreferBadWifi() {
5269 return mMultinetworkPolicyTracker.getActivelyPreferBadWifi();
5270 }
5271
Remi NGUYEN VAN1fb7cab2019-03-22 11:14:13 +09005272 /**
5273 * Return whether the device should maintain continuous, working connectivity by switching away
5274 * from WiFi networks having no connectivity.
5275 * @see MultinetworkPolicyTracker#getAvoidBadWifi()
5276 */
5277 public boolean shouldAvoidBadWifi() {
Remi NGUYEN VAN27de63e2019-01-20 20:35:06 +09005278 if (!checkNetworkStackPermission()) {
5279 throw new SecurityException("avoidBadWifi requires NETWORK_STACK permission");
5280 }
5281 return avoidBadWifi();
5282 }
5283
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005284 private void updateAvoidBadWifi() {
Chalard Jeanbb902a52021-08-18 01:35:19 +09005285 ensureRunningOnConnectivityServiceThread();
5286 // Agent info scores and offer scores depend on whether cells yields to bad wifi.
Chalard Jean1325a632022-09-16 18:01:12 +09005287 final boolean avoidBadWifi = avoidBadWifi();
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005288 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean142f0fe2021-03-31 23:19:05 +09005289 nai.updateScoreForNetworkAgentUpdate();
Chalard Jean1325a632022-09-16 18:01:12 +09005290 if (avoidBadWifi) {
5291 // If the device is now avoiding bad wifi, remove notifications that might have
5292 // been put up when the device didn't.
5293 mNotifier.clearNotification(nai.network.getNetId(), NotificationType.LOST_INTERNET);
5294 }
Chalard Jeanf3ff3622021-03-19 13:49:56 +09005295 }
Chalard Jeanbb902a52021-08-18 01:35:19 +09005296 // UpdateOfferScore will update mNetworkOffers inline, so make a copy first.
5297 final ArrayList<NetworkOfferInfo> offersToUpdate = new ArrayList<>(mNetworkOffers);
5298 for (final NetworkOfferInfo noi : offersToUpdate) {
5299 updateOfferScore(noi.offer);
5300 }
Chalard Jean020b93a2022-09-01 13:20:14 +09005301 mNetworkRanker.setConfiguration(new NetworkRanker.Configuration(activelyPreferBadWifi()));
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09005302 rematchAllNetworksAndRequests();
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005303 }
5304
Erik Kline95ecfee2016-10-02 18:02:14 +09005305 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005306 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005307 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colittiee6c69e2017-01-24 09:41:36 +09005308 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005309 if (!configRestrict) {
5310 pw.println("Bad Wi-Fi avoidance: unrestricted");
5311 return;
5312 }
5313
5314 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
5315 pw.increaseIndent();
Chalard Jeane0fdea32022-09-14 21:44:22 +09005316 pw.println("Config restrict: " + configRestrict);
5317 pw.println("Actively prefer bad wifi: " + activelyPreferBadWifi());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005318
Chalard Jeane0fdea32022-09-14 21:44:22 +09005319 final String settingValue = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005320 String description;
5321 // Can't use a switch statement because strings are legal case labels, but null is not.
Chalard Jeane0fdea32022-09-14 21:44:22 +09005322 if ("0".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005323 description = "get stuck";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005324 } else if (settingValue == null) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005325 description = "prompt";
Chalard Jeane0fdea32022-09-14 21:44:22 +09005326 } else if ("1".equals(settingValue)) {
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005327 description = "avoid";
5328 } else {
Chalard Jeane0fdea32022-09-14 21:44:22 +09005329 description = settingValue + " (?)";
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005330 }
Chalard Jeane0fdea32022-09-14 21:44:22 +09005331 pw.println("Avoid bad wifi setting: " + description);
chiachangwang18a6e8c2022-12-01 00:22:34 +00005332
5333 final Boolean configValue = BinderUtils.withCleanCallingIdentity(
5334 () -> mMultinetworkPolicyTracker.deviceConfigActivelyPreferBadWifi());
Chalard Jeane0fdea32022-09-14 21:44:22 +09005335 if (null == configValue) {
5336 description = "unset";
5337 } else if (configValue) {
5338 description = "force true";
5339 } else {
5340 description = "force false";
5341 }
5342 pw.println("Actively prefer bad wifi conf: " + description);
5343 pw.println();
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005344 pw.println("Network overrides:");
5345 pw.increaseIndent();
Hugo Benichia480ba52018-09-03 08:19:02 +09005346 for (NetworkAgentInfo nai : networksSortedById()) {
Chalard Jean254bd162022-08-25 13:04:51 +09005347 if (0L != nai.getAvoidUnvalidated()) {
Chalard Jean49707572019-12-10 21:07:02 +09005348 pw.println(nai.toShortString());
Lorenzo Colittia4e88082016-09-20 16:03:27 +09005349 }
5350 }
5351 pw.decreaseIndent();
5352 pw.decreaseIndent();
5353 }
5354
paulhu7746e4e2020-06-09 19:07:03 +08005355 // TODO: This method is copied from TetheringNotificationUpdater. Should have a utility class to
5356 // unify the method.
5357 private static @NonNull String getSettingsPackageName(@NonNull final PackageManager pm) {
5358 final Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);
5359 final ComponentName settingsComponent = settingsIntent.resolveActivity(pm);
5360 return settingsComponent != null
5361 ? settingsComponent.getPackageName() : "com.android.settings";
5362 }
5363
lucaslinb1e8e382019-01-24 15:55:30 +08005364 private void showNetworkNotification(NetworkAgentInfo nai, NotificationType type) {
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005365 final String action;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005366 final boolean highPriority;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005367 switch (type) {
5368 case NO_INTERNET:
5369 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005370 // High priority because it is only displayed for explicitly selected networks.
5371 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005372 break;
lucasline117e2e2019-10-22 18:27:33 +08005373 case PRIVATE_DNS_BROKEN:
5374 action = Settings.ACTION_WIRELESS_SETTINGS;
5375 // High priority because we should let user know why there is no internet.
5376 highPriority = true;
5377 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005378 case LOST_INTERNET:
5379 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005380 // High priority because it could help the user avoid unexpected data usage.
5381 highPriority = true;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005382 break;
lucaslin2240ef62019-03-12 13:08:03 +08005383 case PARTIAL_CONNECTIVITY:
5384 action = ConnectivityManager.ACTION_PROMPT_PARTIAL_CONNECTIVITY;
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005385 // Don't bother the user with a high-priority notification if the network was not
5386 // explicitly selected by the user.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005387 highPriority = nai.networkAgentConfig.explicitlySelected;
lucaslin2240ef62019-03-12 13:08:03 +08005388 break;
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005389 default:
Aaron Huang6616df32020-10-30 22:04:25 +08005390 Log.wtf(TAG, "Unknown notification type " + type);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005391 return;
5392 }
5393
5394 Intent intent = new Intent(action);
lucaslin444d43a2020-02-20 16:56:59 +08005395 if (type != NotificationType.PRIVATE_DNS_BROKEN) {
Chiachang Wang08d36912021-03-18 16:20:27 +08005396 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, nai.network);
lucaslinb1e8e382019-01-24 15:55:30 +08005397 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
paulhu7746e4e2020-06-09 19:07:03 +08005398 // Some OEMs have their own Settings package. Thus, need to get the current using
5399 // Settings package name instead of just use default name "com.android.settings".
5400 final String settingsPkgName = getSettingsPackageName(mContext.getPackageManager());
5401 intent.setClassName(settingsPkgName,
5402 settingsPkgName + ".wifi.WifiNoInternetDialog");
lucaslinb1e8e382019-01-24 15:55:30 +08005403 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005404
paulhu2af50222020-10-11 22:52:27 +08005405 PendingIntent pendingIntent = PendingIntent.getActivity(
5406 mContext.createContextAsUser(UserHandle.CURRENT, 0 /* flags */),
paulhu7746e4e2020-06-09 19:07:03 +08005407 0 /* requestCode */,
5408 intent,
paulhu2af50222020-10-11 22:52:27 +08005409 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_IMMUTABLE);
Lorenzo Colitti8a2348f2019-06-05 16:08:37 +09005410
Serik Beketayevec8ad212020-12-07 22:43:07 -08005411 mNotifier.showNotification(
5412 nai.network.getNetId(), type, nai, null, pendingIntent, highPriority);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005413 }
5414
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005415 private boolean shouldPromptUnvalidated(NetworkAgentInfo nai) {
5416 // Don't prompt if the network is validated, and don't prompt on captive portals
5417 // because we're already prompting the user to sign in.
Chalard Jean254bd162022-08-25 13:04:51 +09005418 if (nai.everValidated() || nai.everCaptivePortalDetected()) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005419 return false;
5420 }
5421
5422 // If a network has partial connectivity, always prompt unless the user has already accepted
5423 // partial connectivity and selected don't ask again. This ensures that if the device
5424 // automatically connects to a network that has partial Internet access, the user will
5425 // always be able to use it, either because they've already chosen "don't ask again" or
Chalard Jean254bd162022-08-25 13:04:51 +09005426 // because we have prompted them.
5427 if (nai.partialConnectivity() && !nai.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005428 return true;
5429 }
5430
5431 // If a network has no Internet access, only prompt if the network was explicitly selected
5432 // and if the user has not already told us to use the network regardless of whether it
5433 // validated or not.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09005434 if (nai.networkAgentConfig.explicitlySelected
5435 && !nai.networkAgentConfig.acceptUnvalidated) {
Lorenzo Colitti2fca94f2019-06-04 19:29:50 +09005436 return true;
5437 }
5438
5439 return false;
5440 }
5441
Chalard Jean5fb43c72022-09-08 19:03:14 +09005442 private void handleInitialEvaluationTimeout(@NonNull final Network network) {
5443 if (VDBG || DDBG) log("handleInitialEvaluationTimeout " + network);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005444
Chalard Jean5fb43c72022-09-08 19:03:14 +09005445 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5446 if (null == nai) return;
5447
5448 if (nai.setEvaluated()) {
5449 // If setEvaluated() returned true, the network never had any form of connectivity.
5450 // This may have an impact on request matching if bad WiFi avoidance is off and the
5451 // network was found not to have Internet access.
5452 nai.updateScoreForNetworkAgentUpdate();
5453 rematchAllNetworksAndRequests();
Chalard Jeane9332c42022-09-13 20:46:19 +09005454
5455 // Also, if this is WiFi and it should be preferred actively, now is the time to
5456 // prompt the user that they walked past and connected to a bad WiFi.
5457 if (nai.networkCapabilities.hasTransport(TRANSPORT_WIFI)
5458 && !avoidBadWifi()
5459 && activelyPreferBadWifi()) {
5460 // The notification will be removed if the network validates or disconnects.
5461 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
5462 return;
5463 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005464 }
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005465
Chalard Jean5fb43c72022-09-08 19:03:14 +09005466 if (!shouldPromptUnvalidated(nai)) return;
5467
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005468 // Stop automatically reconnecting to this network in the future. Automatically connecting
5469 // to a network that provides no or limited connectivity is not useful, because the user
5470 // cannot use that network except through the notification shown by this method, and the
5471 // notification is only shown if the network is explicitly selected by the user.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09005472 nai.onPreventAutomaticReconnect();
Lorenzo Colitti2f2b9612019-05-30 16:24:31 +09005473
Chalard Jean254bd162022-08-25 13:04:51 +09005474 if (nai.partialConnectivity()) {
lucasline0118ab2019-03-21 11:59:22 +08005475 showNetworkNotification(nai, NotificationType.PARTIAL_CONNECTIVITY);
lucaslin2240ef62019-03-12 13:08:03 +08005476 } else {
5477 showNetworkNotification(nai, NotificationType.NO_INTERNET);
5478 }
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005479 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005480
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005481 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
5482 NetworkCapabilities nc = nai.networkCapabilities;
Chalard Jean49707572019-12-10 21:07:02 +09005483 if (DBG) log("handleNetworkUnvalidated " + nai.toShortString() + " cap=" + nc);
fionaxu5310c302016-05-23 16:33:16 -07005484
lucaslin2240ef62019-03-12 13:08:03 +08005485 if (!nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
5486 return;
5487 }
5488
5489 if (mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
lucaslinb1e8e382019-01-24 15:55:30 +08005490 showNetworkNotification(nai, NotificationType.LOST_INTERNET);
Lorenzo Colitti199ecfc2016-09-15 14:02:29 +09005491 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005492 }
5493
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005494 @Override
5495 public int getMultipathPreference(Network network) {
5496 enforceAccessPermission();
5497
5498 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkeyadebffc2017-07-12 10:50:42 -06005499 if (nai != null && nai.networkCapabilities
5500 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005501 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
5502 }
5503
Aaron Huang9a57acf2020-12-08 10:03:29 +08005504 final NetworkPolicyManager netPolicyManager =
5505 mContext.getSystemService(NetworkPolicyManager.class);
5506
Remi NGUYEN VANe2139a02021-03-18 14:23:12 +09005507 final long token = Binder.clearCallingIdentity();
5508 final int networkPreference;
5509 try {
5510 networkPreference = netPolicyManager.getMultipathPreference(network);
5511 } finally {
5512 Binder.restoreCallingIdentity(token);
5513 }
Aaron Huang9a57acf2020-12-08 10:03:29 +08005514 if (networkPreference != 0) {
Lorenzo Colitti389a8142018-01-24 17:35:07 +09005515 return networkPreference;
5516 }
Lorenzo Colitti48a2a322017-01-24 18:08:41 +09005517 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
5518 }
5519
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005520 @Override
5521 public NetworkRequest getDefaultRequest() {
Chalard Jean5b409c72021-02-04 13:12:59 +09005522 return mDefaultRequest.mRequests.get(0);
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005523 }
5524
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005525 private class InternalHandler extends Handler {
5526 public InternalHandler(Looper looper) {
5527 super(looper);
5528 }
5529
5530 @Override
5531 public void handleMessage(Message msg) {
Jeff Sharkeya1ef1be2012-07-23 13:19:46 -07005532 switch (msg.what) {
Robert Greenwalt520d6dc2014-06-25 16:45:57 -07005533 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005534 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005535 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwaltcf1a56c2010-09-09 14:05:10 -07005536 break;
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005537 }
Sreeram Ramachandran1b5a3ac2013-08-27 11:41:19 -07005538 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Chalard Jean09335372018-06-08 14:24:49 +09005539 mProxyTracker.loadDeprecatedGlobalHttpProxy();
Robert Greenwalt34848c02011-03-25 13:09:25 -07005540 break;
5541 }
Jason Monka69f1b02013-10-10 14:02:51 -04005542 case EVENT_PROXY_HAS_CHANGED: {
Aaron Huangf9fa0b92021-01-18 15:28:01 +08005543 final Pair<Network, ProxyInfo> arg = (Pair<Network, ProxyInfo>) msg.obj;
5544 handleApplyDefaultProxy(arg.second);
Jason Monka69f1b02013-10-10 14:02:51 -04005545 break;
5546 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005547 case EVENT_REGISTER_NETWORK_PROVIDER: {
5548 handleRegisterNetworkProvider((NetworkProviderInfo) msg.obj);
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07005549 break;
5550 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09005551 case EVENT_UNREGISTER_NETWORK_PROVIDER: {
5552 handleUnregisterNetworkProvider((Messenger) msg.obj);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07005553 break;
5554 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09005555 case EVENT_REGISTER_NETWORK_OFFER: {
5556 handleRegisterNetworkOffer((NetworkOffer) msg.obj);
5557 break;
5558 }
5559 case EVENT_UNREGISTER_NETWORK_OFFER: {
5560 final NetworkOfferInfo offer =
5561 findNetworkOfferInfoByCallback((INetworkOfferCallback) msg.obj);
5562 if (null != offer) {
5563 handleUnregisterNetworkOffer(offer);
5564 }
5565 break;
5566 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005567 case EVENT_REGISTER_NETWORK_AGENT: {
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09005568 final Pair<NetworkAgentInfo, INetworkMonitor> arg =
5569 (Pair<NetworkAgentInfo, INetworkMonitor>) msg.obj;
5570 handleRegisterNetworkAgent(arg.first, arg.second);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07005571 break;
5572 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005573 case EVENT_REGISTER_NETWORK_REQUEST:
5574 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Kline05f2b402015-04-30 12:58:40 +09005575 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005576 break;
5577 }
Paul Jensenc8873fc2015-06-17 14:15:39 -04005578 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
5579 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005580 handleRegisterNetworkRequestWithIntent(msg);
5581 break;
5582 }
Erik Kline155a59a2015-11-25 12:49:38 +09005583 case EVENT_TIMEOUT_NETWORK_REQUEST: {
5584 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
5585 handleTimedOutNetworkRequest(nri);
5586 break;
5587 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08005588 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
5589 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
5590 break;
5591 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005592 case EVENT_RELEASE_NETWORK_REQUEST: {
Etan Cohenfbfdd842019-01-08 12:09:18 -08005593 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1,
5594 /* callOnUnavailable */ false);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005595 break;
5596 }
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005597 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichif4210292017-04-21 15:07:12 +09005598 Network network = (Network) msg.obj;
5599 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005600 break;
5601 }
lucaslin2240ef62019-03-12 13:08:03 +08005602 case EVENT_SET_ACCEPT_PARTIAL_CONNECTIVITY: {
5603 Network network = (Network) msg.obj;
5604 handleSetAcceptPartialConnectivity(network, toBool(msg.arg1),
5605 toBool(msg.arg2));
5606 break;
5607 }
Lorenzo Colittic65750c2016-09-19 01:00:19 +09005608 case EVENT_SET_AVOID_UNVALIDATED: {
5609 handleSetAvoidUnvalidated((Network) msg.obj);
5610 break;
5611 }
Chalard Jean5fb43c72022-09-08 19:03:14 +09005612 case EVENT_INITIAL_EVALUATION_TIMEOUT: {
5613 handleInitialEvaluationTimeout((Network) msg.obj);
Lorenzo Colitti6947c062015-04-03 16:38:52 +09005614 break;
5615 }
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07005616 case EVENT_CONFIGURE_ALWAYS_ON_NETWORKS: {
5617 handleConfigureAlwaysOnNetworks();
Erik Kline05f2b402015-04-30 12:58:40 +09005618 break;
5619 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005620 // Sent by AutomaticOnOffKeepaliveTracker to process an app request on the
5621 // handler thread.
5622 case AutomaticOnOffKeepaliveTracker.CMD_REQUEST_START_KEEPALIVE: {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005623 mKeepaliveTracker.handleStartKeepalive(msg);
5624 break;
5625 }
chiachangwangf1b1fb42023-04-14 07:32:43 +00005626 case AutomaticOnOffKeepaliveTracker.CMD_MONITOR_AUTOMATIC_KEEPALIVE: {
Chalard Jean98732db2023-02-03 21:26:59 +09005627 final AutomaticOnOffKeepalive ki =
5628 mKeepaliveTracker.getKeepaliveForBinder((IBinder) msg.obj);
5629 if (null == ki) return; // The callback was unregistered before the alarm fired
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005630
chiachangwang676c84e2023-02-14 09:22:05 +00005631 final Network underpinnedNetwork = ki.getUnderpinnedNetwork();
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005632 final Network network = ki.getNetwork();
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005633 boolean networkFound = false;
chiachangwang676c84e2023-02-14 09:22:05 +00005634 boolean underpinnedNetworkFound = false;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005635 for (NetworkAgentInfo n : mNetworkAgentInfos) {
5636 if (n.network.equals(network)) networkFound = true;
chiachangwang676c84e2023-02-14 09:22:05 +00005637 if (n.everConnected() && n.network.equals(underpinnedNetwork)) {
5638 underpinnedNetworkFound = true;
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005639 }
5640 }
5641
5642 // If the network no longer exists, then the keepalive should have been
5643 // cleaned up already. There is no point trying to resume keepalives.
5644 if (!networkFound) return;
5645
chiachangwang676c84e2023-02-14 09:22:05 +00005646 if (underpinnedNetworkFound) {
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005647 mKeepaliveTracker.handleMonitorAutomaticKeepalive(ki,
chiachangwang676c84e2023-02-14 09:22:05 +00005648 underpinnedNetwork.netId);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005649 } else {
chiachangwang676c84e2023-02-14 09:22:05 +00005650 // If no underpinned network, then make sure the keepalive is running.
Chalard Jean23f1bfd2023-01-24 17:11:27 +09005651 mKeepaliveTracker.handleMaybeResumeKeepalive(ki);
chiachangwang9ef4ffe2023-01-18 01:19:27 +00005652 }
5653 break;
5654 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005655 // Sent by KeepaliveTracker to process an app request on the state machine thread.
junyulai011b1f12019-01-03 18:50:15 +08005656 case NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE: {
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005657 final AutomaticOnOffKeepalive ki = mKeepaliveTracker.getKeepaliveForBinder(
5658 (IBinder) msg.obj);
5659 if (ki == null) {
5660 Log.e(TAG, "Attempt to stop an already stopped keepalive");
chiachangwangd50f9512023-01-31 06:56:13 +00005661 return;
5662 }
Chalard Jeanf0b261e2023-02-03 22:11:20 +09005663 final int reason = msg.arg2;
5664 mKeepaliveTracker.handleStopKeepalive(ki, reason);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09005665 break;
5666 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005667 case EVENT_REPORT_NETWORK_CONNECTIVITY: {
5668 handleReportNetworkConnectivity((NetworkAgentInfo) msg.obj, msg.arg1,
5669 toBool(msg.arg2));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005670 break;
5671 }
Erik Kline31b4a9e2018-01-11 21:07:29 +09005672 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
5673 handlePrivateDnsSettingsChanged();
5674 break;
dalyk1720e542018-03-05 12:42:22 -05005675 case EVENT_PRIVATE_DNS_VALIDATION_UPDATE:
5676 handlePrivateDnsValidationUpdate(
5677 (PrivateDnsValidationUpdate) msg.obj);
5678 break;
Sudheer Shanka9967d462021-03-18 19:09:25 +00005679 case EVENT_UID_BLOCKED_REASON_CHANGED:
5680 handleUidBlockedReasonChanged(msg.arg1, msg.arg2);
junyulaif2c67e42018-08-07 19:50:45 +08005681 break;
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09005682 case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
5683 handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
5684 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005685 case EVENT_SET_OEM_NETWORK_PREFERENCE: {
Chalard Jean6010c002021-03-03 16:37:13 +09005686 final Pair<OemNetworkPreferences, IOnCompleteListener> arg =
5687 (Pair<OemNetworkPreferences, IOnCompleteListener>) msg.obj;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005688 handleSetOemNetworkPreference(arg.first, arg.second);
James Mattis45d81842021-01-10 14:24:24 -08005689 break;
Chalard Jean5d6e23b2021-03-01 22:00:20 +09005690 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005691 case EVENT_SET_PROFILE_NETWORK_PREFERENCE: {
Chalard Jean0606fc82022-12-14 20:34:43 +09005692 final Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener> arg =
5693 (Pair<List<ProfileNetworkPreferenceInfo>, IOnCompleteListener>) msg.obj;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005694 handleSetProfileNetworkPreference(arg.first, arg.second);
paulhucbe2b262021-05-05 11:04:59 +08005695 break;
Chalard Jeanb5a139f2021-02-25 21:46:34 +09005696 }
lucaslin1193a5d2021-01-21 02:04:15 +08005697 case EVENT_REPORT_NETWORK_ACTIVITY:
5698 mNetworkActivityTracker.handleReportNetworkActivity();
5699 break;
paulhu51f77dc2021-06-07 02:34:20 +00005700 case EVENT_MOBILE_DATA_PREFERRED_UIDS_CHANGED:
5701 handleMobileDataPreferredUidsChanged();
5702 break;
Chiachang Wang6eac9fb2021-06-17 22:11:30 +08005703 case EVENT_SET_TEST_ALLOW_BAD_WIFI_UNTIL:
5704 final long timeMs = ((Long) msg.obj).longValue();
5705 mMultinetworkPolicyTracker.setTestAllowBadWifiUntil(timeMs);
5706 break;
Patrick Rohr2857ac42022-01-21 14:58:16 +01005707 case EVENT_INGRESS_RATE_LIMIT_CHANGED:
5708 handleIngressRateLimitChanged();
5709 break;
Hansen Kurli55396972022-10-28 03:31:17 +00005710 case EVENT_USER_DOES_NOT_WANT:
5711 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
5712 if (nai == null) break;
5713 nai.onPreventAutomaticReconnect();
5714 nai.disconnect();
5715 break;
lucaslin3ba7cc22022-12-19 02:35:33 +00005716 case EVENT_SET_VPN_NETWORK_PREFERENCE:
5717 handleSetVpnNetworkPreference((VpnNetworkPreferenceInfo) msg.obj);
5718 break;
chiachangwange0192a72023-02-06 13:25:01 +00005719 case EVENT_SET_LOW_TCP_POLLING_UNTIL: {
5720 final long time = ((Long) msg.obj).longValue();
5721 mKeepaliveTracker.handleSetTestLowTcpPollingTimer(time);
5722 break;
5723 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08005724 }
5725 }
5726 }
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005727
Lorenzo Colittid6459092016-07-04 12:55:44 +09005728 @Override
markchien5776f962019-12-16 20:15:20 +08005729 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005730 public int getLastTetherError(String iface) {
markchien28160b32021-09-29 22:57:31 +08005731 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005732 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5733 Context.TETHERING_SERVICE);
5734 return tm.getLastTetherError(iface);
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005735 }
5736
Lorenzo Colittid6459092016-07-04 12:55:44 +09005737 @Override
markchien5776f962019-12-16 20:15:20 +08005738 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005739 public String[] getTetherableIfaces() {
markchien28160b32021-09-29 22:57:31 +08005740 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005741 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5742 Context.TETHERING_SERVICE);
5743 return tm.getTetherableIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005744 }
5745
Lorenzo Colittid6459092016-07-04 12:55:44 +09005746 @Override
markchien5776f962019-12-16 20:15:20 +08005747 @Deprecated
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005748 public String[] getTetheredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005749 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005750 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5751 Context.TETHERING_SERVICE);
5752 return tm.getTetheredIfaces();
Robert Greenwalt0c4828c2010-01-26 11:40:34 -08005753 }
Robert Greenwalt8e87f122010-02-11 18:18:40 -08005754
markchien5776f962019-12-16 20:15:20 +08005755
Lorenzo Colittid6459092016-07-04 12:55:44 +09005756 @Override
markchien5776f962019-12-16 20:15:20 +08005757 @Deprecated
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005758 public String[] getTetheringErroredIfaces() {
markchien28160b32021-09-29 22:57:31 +08005759 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005760 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5761 Context.TETHERING_SERVICE);
5762
5763 return tm.getTetheringErroredIfaces();
Robert Greenwalt4283ded2010-03-02 17:25:02 -08005764 }
5765
Lorenzo Colittid6459092016-07-04 12:55:44 +09005766 @Override
markchien5776f962019-12-16 20:15:20 +08005767 @Deprecated
5768 public String[] getTetherableUsbRegexs() {
markchien28160b32021-09-29 22:57:31 +08005769 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005770 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5771 Context.TETHERING_SERVICE);
5772
5773 return tm.getTetherableUsbRegexs();
Robert Greenwalte594a762014-06-23 14:53:42 -07005774 }
5775
Udam Saini8f7d6a72017-06-07 12:06:28 -07005776 @Override
markchien5776f962019-12-16 20:15:20 +08005777 @Deprecated
5778 public String[] getTetherableWifiRegexs() {
markchien28160b32021-09-29 22:57:31 +08005779 enforceAccessPermission();
markchien5776f962019-12-16 20:15:20 +08005780 final TetheringManager tm = (TetheringManager) mContext.getSystemService(
5781 Context.TETHERING_SERVICE);
5782 return tm.getTetherableWifiRegexs();
markchien4ef53e82019-02-27 14:56:11 +08005783 }
5784
Robert Greenwalte0b00512014-07-02 09:59:16 -07005785 // Called when we lose the default network and have no replacement yet.
5786 // This will automatically be cleared after X seconds or a new default network
5787 // becomes CONNECTED, whichever happens first. The timer is started by the
5788 // first caller and not restarted by subsequent callers.
Hugo Benichi471b62a2017-03-30 23:18:10 +09005789 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005790 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005791 if (mNetTransitionWakeLock.isHeld()) {
5792 return;
5793 }
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005794 mNetTransitionWakeLock.acquire();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005795 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
5796 mTotalWakelockAcquisitions++;
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005797 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005798 mWakelockLogs.log("ACQUIRE for " + forWhom);
5799 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005800 final int lockTimeout = mResources.get().getInteger(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09005801 R.integer.config_networkTransitionTimeout);
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09005802 mHandler.sendMessageDelayed(msg, lockTimeout);
Robert Greenwalt93dc1042010-06-15 12:19:37 -07005803 }
Robert Greenwalt24118e82010-09-09 13:15:32 -07005804
Hugo Benichi471b62a2017-03-30 23:18:10 +09005805 // Called when we gain a new default network to release the network transition wakelock in a
5806 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
5807 // message is cancelled.
5808 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichi47011212017-03-30 10:46:05 +09005809 synchronized (this) {
Hugo Benichi471b62a2017-03-30 23:18:10 +09005810 if (!mNetTransitionWakeLock.isHeld()) {
5811 return; // expiry message released the lock first.
Hugo Benichi47011212017-03-30 10:46:05 +09005812 }
5813 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005814 // Cancel self timeout on wakelock hold.
5815 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
5816 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
5817 mHandler.sendMessageDelayed(msg, 1000);
5818 }
5819
5820 // Called when either message of ensureNetworkTransitionWakelock or
5821 // scheduleReleaseNetworkTransitionWakelock is processed.
5822 private void handleReleaseNetworkTransitionWakelock(int eventId) {
5823 String event = eventName(eventId);
5824 synchronized (this) {
5825 if (!mNetTransitionWakeLock.isHeld()) {
5826 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
Aaron Huang6616df32020-10-30 22:04:25 +08005827 Log.w(TAG, "expected Net Transition WakeLock to be held");
Hugo Benichi471b62a2017-03-30 23:18:10 +09005828 return;
5829 }
5830 mNetTransitionWakeLock.release();
Hugo Benichi88f49ac2017-09-05 13:25:07 +09005831 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
5832 mTotalWakelockDurationMs += lockDuration;
5833 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
5834 mTotalWakelockReleases++;
Hugo Benichi47011212017-03-30 10:46:05 +09005835 }
Hugo Benichi471b62a2017-03-30 23:18:10 +09005836 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichi47011212017-03-30 10:46:05 +09005837 }
5838
Robert Greenwalt986c7412010-09-08 15:24:47 -07005839 // 100 percent is full good, 0 is full bad.
Lorenzo Colittid6459092016-07-04 12:55:44 +09005840 @Override
Robert Greenwalt986c7412010-09-08 15:24:47 -07005841 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwalta1d68e72014-08-06 21:32:18 -07005842 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti4e858cb2015-02-11 07:39:20 +09005843 if (nai == null) return;
Paul Jensenb95d7952015-04-07 12:43:13 -04005844 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt6a2db8a2010-09-23 10:05:56 -07005845 }
5846
Lorenzo Colittid6459092016-07-04 12:55:44 +09005847 @Override
Paul Jensenb95d7952015-04-07 12:43:13 -04005848 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen83f5d572014-08-29 09:54:01 -04005849 enforceAccessPermission();
5850 enforceInternetPermission();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005851 final int uid = mDeps.getCallingUid();
Hugo Benichif4210292017-04-21 15:07:12 +09005852 final int connectivityInfo = encodeBool(hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005853
5854 final NetworkAgentInfo nai;
5855 if (network == null) {
Chalard Jean5b409c72021-02-04 13:12:59 +09005856 nai = getDefaultNetwork();
Cody Kesting5a9a2ae2020-01-07 11:18:54 -08005857 } else {
5858 nai = getNetworkAgentInfoForNetwork(network);
5859 }
Cody Kesting3d1df812020-06-25 11:13:39 -07005860
5861 mHandler.sendMessage(
Cody Kestingf1120be2020-08-03 18:01:40 -07005862 mHandler.obtainMessage(
5863 EVENT_REPORT_NETWORK_CONNECTIVITY, uid, connectivityInfo, nai));
Hugo Benichid6b510a2017-04-06 17:22:18 +09005864 }
Paul Jensen83f5d572014-08-29 09:54:01 -04005865
Hugo Benichid6b510a2017-04-06 17:22:18 +09005866 private void handleReportNetworkConnectivity(
Cody Kestingf1120be2020-08-03 18:01:40 -07005867 @Nullable NetworkAgentInfo nai, int uid, boolean hasConnectivity) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005868 if (nai == null
5869 || nai != getNetworkAgentInfoForNetwork(nai.network)
Cody Kestingf1120be2020-08-03 18:01:40 -07005870 || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
Paul Jensen3c3c6e82015-06-25 10:28:34 -04005871 return;
5872 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005873 // Revalidate if the app report does not match our current validated state.
Chalard Jean254bd162022-08-25 13:04:51 +09005874 if (hasConnectivity == nai.isValidated()) {
Cody Kestingf1120be2020-08-03 18:01:40 -07005875 mConnectivityDiagnosticsHandler.sendMessage(
5876 mConnectivityDiagnosticsHandler.obtainMessage(
5877 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5878 new ReportedNetworkConnectivityInfo(
5879 hasConnectivity, false /* isNetworkRevalidating */, uid, nai)));
Hugo Benichie9d321b2017-04-06 16:01:44 +09005880 return;
5881 }
Paul Jensenb95d7952015-04-07 12:43:13 -04005882 if (DBG) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08005883 int netid = nai.network.getNetId();
Hugo Benichid6b510a2017-04-06 17:22:18 +09005884 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenb95d7952015-04-07 12:43:13 -04005885 }
Hugo Benichie9d321b2017-04-06 16:01:44 +09005886 // Validating a network that has not yet connected could result in a call to
5887 // rematchNetworkAndRequests() which is not meant to work on such networks.
Chalard Jean254bd162022-08-25 13:04:51 +09005888 if (!nai.everConnected()) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005889 return;
Paul Jensen83f5d572014-08-29 09:54:01 -04005890 }
paulhu7aeba372020-12-30 00:42:19 +08005891 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
5892 if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
Hugo Benichie9d321b2017-04-06 16:01:44 +09005893 return;
5894 }
Cody Kestingf1120be2020-08-03 18:01:40 -07005895
5896 // Send CONNECTIVITY_REPORTED event before re-validating the Network to force an ordering of
5897 // ConnDiags events. This ensures that #onNetworkConnectivityReported() will be called
5898 // before #onConnectivityReportAvailable(), which is called once Network evaluation is
5899 // completed.
5900 mConnectivityDiagnosticsHandler.sendMessage(
5901 mConnectivityDiagnosticsHandler.obtainMessage(
5902 ConnectivityDiagnosticsHandler.EVENT_NETWORK_CONNECTIVITY_REPORTED,
5903 new ReportedNetworkConnectivityInfo(
5904 hasConnectivity, true /* isNetworkRevalidating */, uid, nai)));
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09005905 nai.networkMonitor().forceReevaluation(uid);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07005906 }
5907
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005908 // TODO: call into netd.
5909 private boolean queryUserAccess(int uid, Network network) {
5910 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5911 if (nai == null) return false;
5912
5913 // Any UID can use its default network.
5914 if (nai == getDefaultNetworkForUid(uid)) return true;
5915
5916 // Privileged apps can use any network.
5917 if (mPermissionMonitor.hasRestrictedNetworksPermission(uid)) {
5918 return true;
5919 }
5920
5921 // An unprivileged UID can use a VPN iff the VPN applies to it.
5922 if (nai.isVPN()) {
5923 return nai.networkCapabilities.appliesToUid(uid);
5924 }
5925
5926 // An unprivileged UID can bypass the VPN that applies to it only if it can protect its
5927 // sockets, i.e., if it is the owner.
5928 final NetworkAgentInfo vpn = getVpnForUid(uid);
5929 if (vpn != null && !vpn.networkAgentConfig.allowBypass
5930 && uid != vpn.networkCapabilities.getOwnerUid()) {
5931 return false;
5932 }
5933
5934 // The UID's permission must be at least sufficient for the network. Since the restricted
5935 // permission was already checked above, that just leaves background networks.
5936 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
5937 return mPermissionMonitor.hasUseBackgroundNetworksPermission(uid);
5938 }
5939
5940 // Unrestricted network. Anyone gets to use it.
5941 return true;
5942 }
5943
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005944 /**
5945 * Returns information about the proxy a certain network is using. If given a null network, it
5946 * it will return the proxy for the bound network for the caller app or the default proxy if
5947 * none.
5948 *
5949 * @param network the network we want to get the proxy information for.
5950 * @return Proxy information if a network has a proxy configured, or otherwise null.
5951 */
Lorenzo Colittid6459092016-07-04 12:55:44 +09005952 @Override
Paul Jensendb93dd92015-05-06 07:32:40 -04005953 public ProxyInfo getProxyForNetwork(Network network) {
Chalard Jean777e2e52018-06-07 18:02:37 +09005954 final ProxyInfo globalProxy = mProxyTracker.getGlobalProxy();
Paul Jensendb93dd92015-05-06 07:32:40 -04005955 if (globalProxy != null) return globalProxy;
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005956 if (network == null) {
5957 // Get the network associated with the calling UID.
Lorenzo Colittif61ca942020-12-15 11:02:22 +09005958 final Network activeNetwork = getActiveNetworkForUidInternal(mDeps.getCallingUid(),
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005959 true);
5960 if (activeNetwork == null) {
5961 return null;
5962 }
5963 return getLinkPropertiesProxyInfo(activeNetwork);
Lorenzo Colitti22c677e2021-03-23 21:01:07 +09005964 } else if (mDeps.queryUserAccess(mDeps.getCallingUid(), network, this)) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005965 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
5966 // caller may not have.
5967 return getLinkPropertiesProxyInfo(network);
5968 }
5969 // No proxy info available if the calling UID does not have network access.
5970 return null;
5971 }
5972
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005973
5974 private ProxyInfo getLinkPropertiesProxyInfo(Network network) {
Paul Jensendb93dd92015-05-06 07:32:40 -04005975 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
5976 if (nai == null) return null;
5977 synchronized (nai) {
Irina Dumitrescude132bb2018-12-05 16:19:47 +00005978 final ProxyInfo linkHttpProxy = nai.linkProperties.getHttpProxy();
5979 return linkHttpProxy == null ? null : new ProxyInfo(linkHttpProxy);
Paul Jensendb93dd92015-05-06 07:32:40 -04005980 }
5981 }
5982
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005983 @Override
Chalard Jean48d60ea2021-03-17 17:03:34 +09005984 public void setGlobalProxy(@Nullable final ProxyInfo proxyProperties) {
paulhu3ffffe72021-09-16 10:15:22 +08005985 enforceNetworkStackPermission(mContext);
Chalard Jean8cbd2dd2018-06-07 18:37:59 +09005986 mProxyTracker.setGlobalProxy(proxyProperties);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005987 }
5988
Chalard Jean777e2e52018-06-07 18:02:37 +09005989 @Override
5990 @Nullable
Jason Monk4d5e20f2014-04-25 15:00:09 -04005991 public ProxyInfo getGlobalProxy() {
Chalard Jean777e2e52018-06-07 18:02:37 +09005992 return mProxyTracker.getGlobalProxy();
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07005993 }
5994
Junyu Lai970963e2022-10-25 15:46:47 +08005995 private void handleApplyDefaultProxy(@Nullable ProxyInfo proxy) {
Jason Monka5bf2842013-07-03 17:04:33 -04005996 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard6ff743e2014-11-20 14:35:32 -05005997 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh763a11c2011-10-03 15:34:04 -07005998 proxy = null;
5999 }
Chalard Jeand9e70ac2018-06-08 12:20:15 +09006000 mProxyTracker.setDefaultProxy(proxy);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006001 }
6002
Irina Dumitrescude132bb2018-12-05 16:19:47 +00006003 // If the proxy has changed from oldLp to newLp, resend proxy broadcast. This method gets called
6004 // when any network changes proxy.
6005 // TODO: Remove usage of broadcast extras as they are deprecated and not applicable in a
6006 // multi-network world where an app might be bound to a non-default network.
Junyu Lai970963e2022-10-25 15:46:47 +08006007 private void updateProxy(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp) {
6008 ProxyInfo newProxyInfo = newLp.getHttpProxy();
Paul Jensenc0618a62014-12-10 15:12:18 -05006009 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
6010
Chalard Jean7d97afc2018-06-07 17:41:29 +09006011 if (!ProxyTracker.proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
Chalard Jean110cb122018-06-08 19:46:44 +09006012 mProxyTracker.sendProxyBroadcast();
Paul Jensenc0618a62014-12-10 15:12:18 -05006013 }
6014 }
6015
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006016 private static class SettingsObserver extends ContentObserver {
Erik Kline05f2b402015-04-30 12:58:40 +09006017 final private HashMap<Uri, Integer> mUriEventMap;
6018 final private Context mContext;
6019 final private Handler mHandler;
6020
6021 SettingsObserver(Context context, Handler handler) {
6022 super(null);
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006023 mUriEventMap = new HashMap<>();
Erik Kline05f2b402015-04-30 12:58:40 +09006024 mContext = context;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006025 mHandler = handler;
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006026 }
6027
Erik Kline05f2b402015-04-30 12:58:40 +09006028 void observe(Uri uri, int what) {
6029 mUriEventMap.put(uri, what);
6030 final ContentResolver resolver = mContext.getContentResolver();
6031 resolver.registerContentObserver(uri, false, this);
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006032 }
6033
6034 @Override
6035 public void onChange(boolean selfChange) {
Aaron Huang6616df32020-10-30 22:04:25 +08006036 Log.wtf(TAG, "Should never be reached.");
Erik Kline05f2b402015-04-30 12:58:40 +09006037 }
6038
6039 @Override
6040 public void onChange(boolean selfChange, Uri uri) {
6041 final Integer what = mUriEventMap.get(uri);
6042 if (what != null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006043 mHandler.obtainMessage(what).sendToTarget();
Erik Kline05f2b402015-04-30 12:58:40 +09006044 } else {
6045 loge("No matching event to send for URI=" + uri);
6046 }
Robert Greenwaltc3c5f862010-10-11 16:00:27 -07006047 }
6048 }
Wink Savillee70c6f52010-12-03 12:01:38 -08006049
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006050 private static void log(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006051 Log.d(TAG, s);
6052 }
6053
6054 private static void logw(String s) {
6055 Log.w(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006056 }
6057
Daniel Brightf9e945b2020-06-15 16:10:01 -07006058 private static void logwtf(String s) {
6059 Log.wtf(TAG, s);
6060 }
6061
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +09006062 private static void logwtf(String s, Throwable t) {
6063 Log.wtf(TAG, s, t);
6064 }
6065
Jeff Sharkey6b9021d2012-07-26 18:32:30 -07006066 private static void loge(String s) {
Aaron Huang6616df32020-10-30 22:04:25 +08006067 Log.e(TAG, s);
Wink Savillee70c6f52010-12-03 12:01:38 -08006068 }
Chia-chi Yeh9a4ad7d2011-05-23 17:26:46 -07006069
Hugo Benichi39621362017-02-11 17:04:43 +09006070 private static void loge(String s, Throwable t) {
Aaron Huang6616df32020-10-30 22:04:25 +08006071 Log.e(TAG, s, t);
Hugo Benichi39621362017-02-11 17:04:43 +09006072 }
6073
Chia-chi Yeh75cacd52011-06-15 17:07:27 -07006074 /**
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006075 * Return the information of all ongoing VPNs.
6076 *
6077 * <p>This method is used to update NetworkStatsService.
6078 *
6079 * <p>Must be called on the handler thread.
Wenchao Tonge164e002015-03-04 13:26:38 -08006080 */
junyulai2050bed2021-01-23 09:46:34 +08006081 private UnderlyingNetworkInfo[] getAllVpnInfo() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08006082 ensureRunningOnConnectivityServiceThread();
Lorenzo Colitticd675292021-02-04 17:32:07 +09006083 if (mLockdownEnabled) {
6084 return new UnderlyingNetworkInfo[0];
Wenchao Tonge164e002015-03-04 13:26:38 -08006085 }
junyulai2050bed2021-01-23 09:46:34 +08006086 List<UnderlyingNetworkInfo> infoList = new ArrayList<>();
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006087 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulai2050bed2021-01-23 09:46:34 +08006088 UnderlyingNetworkInfo info = createVpnInfo(nai);
Lorenzo Colitti70b3b912020-12-15 15:47:24 +09006089 if (info != null) {
6090 infoList.add(info);
6091 }
6092 }
junyulai2050bed2021-01-23 09:46:34 +08006093 return infoList.toArray(new UnderlyingNetworkInfo[infoList.size()]);
Wenchao Tonge164e002015-03-04 13:26:38 -08006094 }
6095
6096 /**
6097 * @return VPN information for accounting, or null if we can't retrieve all required
Benedict Wong34857f82019-06-12 17:46:15 +00006098 * information, e.g underlying ifaces.
Wenchao Tonge164e002015-03-04 13:26:38 -08006099 */
junyulai2050bed2021-01-23 09:46:34 +08006100 private UnderlyingNetworkInfo createVpnInfo(NetworkAgentInfo nai) {
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006101 Network[] underlyingNetworks = nai.declaredUnderlyingNetworks;
Wenchao Tonge164e002015-03-04 13:26:38 -08006102 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
6103 // the underlyingNetworks list.
Lorenzo Colittibd079452021-07-02 11:47:57 +09006104 // TODO: stop using propagateUnderlyingCapabilities here, for example, by always
6105 // initializing NetworkAgentInfo#declaredUnderlyingNetworks to an empty array.
6106 if (underlyingNetworks == null && nai.propagateUnderlyingCapabilities()) {
James Mattis2516da32021-01-31 17:06:19 -08006107 final NetworkAgentInfo defaultNai = getDefaultNetworkForUid(
6108 nai.networkCapabilities.getOwnerUid());
Benedict Wong9308cd32019-06-12 17:46:31 +00006109 if (defaultNai != null) {
Benedict Wong34857f82019-06-12 17:46:15 +00006110 underlyingNetworks = new Network[] { defaultNai.network };
Wenchao Tonge164e002015-03-04 13:26:38 -08006111 }
6112 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006113
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006114 if (CollectionUtils.isEmpty(underlyingNetworks)) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006115
6116 List<String> interfaces = new ArrayList<>();
6117 for (Network network : underlyingNetworks) {
6118 NetworkAgentInfo underlyingNai = getNetworkAgentInfoForNetwork(network);
6119 if (underlyingNai == null) continue;
6120 LinkProperties lp = underlyingNai.linkProperties;
6121 for (String iface : lp.getAllInterfaceNames()) {
6122 if (!TextUtils.isEmpty(iface)) {
6123 interfaces.add(iface);
Benedict Wong34857f82019-06-12 17:46:15 +00006124 }
6125 }
Benedict Wong34857f82019-06-12 17:46:15 +00006126 }
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006127
6128 if (interfaces.isEmpty()) return null;
6129
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006130 // Must be non-null or NetworkStatsService will crash.
6131 // Cannot happen in production code because Vpn only registers the NetworkAgent after the
6132 // tun or ipsec interface is created.
junyulai2050bed2021-01-23 09:46:34 +08006133 // TODO: Remove this check.
junyulaiacb32972021-01-23 01:09:11 +08006134 if (nai.linkProperties.getInterfaceName() == null) return null;
Lorenzo Colittifee5e4e2020-11-17 15:58:21 +09006135
junyulai2050bed2021-01-23 09:46:34 +08006136 return new UnderlyingNetworkInfo(nai.networkCapabilities.getOwnerUid(),
6137 nai.linkProperties.getInterfaceName(), interfaces);
Wenchao Tonge164e002015-03-04 13:26:38 -08006138 }
6139
James Mattisd31bdfa2020-12-23 16:37:26 -08006140 // TODO This needs to be the default network that applies to the NAI.
James Mattis2516da32021-01-31 17:06:19 -08006141 private Network[] underlyingNetworksOrDefault(final int ownerUid,
6142 Network[] underlyingNetworks) {
6143 final Network defaultNetwork = getNetwork(getDefaultNetworkForUid(ownerUid));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006144 if (underlyingNetworks == null && defaultNetwork != null) {
6145 // null underlying networks means to track the default.
6146 underlyingNetworks = new Network[] { defaultNetwork };
6147 }
6148 return underlyingNetworks;
6149 }
6150
6151 // Returns true iff |network| is an underlying network of |nai|.
6152 private boolean hasUnderlyingNetwork(NetworkAgentInfo nai, Network network) {
6153 // TODO: support more than one level of underlying networks, either via a fixed-depth search
6154 // (e.g., 2 levels of underlying networks), or via loop detection, or....
Lorenzo Colittibd079452021-07-02 11:47:57 +09006155 if (!nai.propagateUnderlyingCapabilities()) return false;
James Mattis2516da32021-01-31 17:06:19 -08006156 final Network[] underlying = underlyingNetworksOrDefault(
6157 nai.networkCapabilities.getOwnerUid(), nai.declaredUnderlyingNetworks);
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006158 return CollectionUtils.contains(underlying, network);
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006159 }
6160
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006161 /**
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006162 * Recompute the capabilities for any networks that had a specific network as underlying.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006163 *
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006164 * When underlying networks change, such networks may have to update capabilities to reflect
6165 * things like the metered bit, their transports, and so on. The capabilities are calculated
6166 * immediately. This method runs on the ConnectivityService thread.
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006167 */
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006168 private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09006169 ensureRunningOnConnectivityServiceThread();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006170 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09006171 if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09006172 updateCapabilitiesForNetwork(nai);
Chalard Jeand4f01ca2018-05-18 22:02:56 +09006173 }
6174 }
6175 }
6176
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006177 private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
6178 // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
6179 // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
6180 // a VPN is not up.
6181 final NetworkAgentInfo vpnNai = getVpnForUid(uid);
6182 if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
6183 for (UidRange range : blockedUidRanges) {
6184 if (range.contains(uid)) return true;
6185 }
6186 return false;
6187 }
6188
6189 @Override
6190 public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
lucasline257bce2021-03-22 11:51:27 +08006191 enforceNetworkStackOrSettingsPermission();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006192 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
6193 encodeBool(requireVpn), 0 /* arg2 */, ranges));
6194 }
6195
6196 private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
6197 if (DBG) {
6198 Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
6199 + Arrays.toString(ranges));
6200 }
6201 // Cannot use a Set since the list of UID ranges might contain duplicates.
6202 final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
6203 for (int i = 0; i < ranges.length; i++) {
6204 if (requireVpn) {
6205 newVpnBlockedUidRanges.add(ranges[i]);
6206 } else {
6207 newVpnBlockedUidRanges.remove(ranges[i]);
6208 }
6209 }
6210
6211 try {
6212 mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
6213 } catch (RemoteException | ServiceSpecificException e) {
6214 Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
6215 + Arrays.toString(ranges) + "): netd command failed: " + e);
6216 }
6217
Motomu Utsumib08654c2022-05-11 05:56:26 +00006218 if (SdkLevel.isAtLeastT()) {
6219 mPermissionMonitor.updateVpnLockdownUidRanges(requireVpn, ranges);
6220 }
6221
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006222 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
6223 final boolean curMetered = nai.networkCapabilities.isMetered();
Sudheer Shanka9967d462021-03-18 19:09:25 +00006224 maybeNotifyNetworkBlocked(nai, curMetered, curMetered,
6225 mVpnBlockedUidRanges, newVpnBlockedUidRanges);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09006226 }
6227
6228 mVpnBlockedUidRanges = newVpnBlockedUidRanges;
6229 }
6230
Jeff Sharkeyebcc7972012-08-25 00:05:46 -07006231 @Override
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006232 public void setLegacyLockdownVpnEnabled(boolean enabled) {
lucasline257bce2021-03-22 11:51:27 +08006233 enforceNetworkStackOrSettingsPermission();
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006234 mHandler.post(() -> mLockdownEnabled = enabled);
Charles He9369e612017-05-15 17:07:18 +01006235 }
6236
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006237 private boolean isLegacyLockdownNai(NetworkAgentInfo nai) {
6238 return mLockdownEnabled
6239 && getVpnType(nai) == VpnManager.TYPE_VPN_LEGACY
6240 && nai.networkCapabilities.appliesToUid(Process.FIRST_APPLICATION_UID);
Robin Leee5d5ed52016-01-05 18:03:46 +00006241 }
6242
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006243 private NetworkAgentInfo getLegacyLockdownNai() {
6244 if (!mLockdownEnabled) {
6245 return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006246 }
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006247 // The legacy lockdown VPN always only applies to userId 0.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006248 final NetworkAgentInfo nai = getVpnForUid(Process.FIRST_APPLICATION_UID);
6249 if (nai == null || !isLegacyLockdownNai(nai)) return null;
Robin Leee5d5ed52016-01-05 18:03:46 +00006250
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006251 // The legacy lockdown VPN must always have exactly one underlying network.
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006252 // This code may run on any thread and declaredUnderlyingNetworks may change, so store it in
6253 // a local variable. There is no need to make a copy because its contents cannot change.
6254 final Network[] underlying = nai.declaredUnderlyingNetworks;
6255 if (underlying == null || underlying.length != 1) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006256 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006257 }
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006258
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006259 // The legacy lockdown VPN always uses the default network.
6260 // If the VPN's underlying network is no longer the current default network, it means that
6261 // the default network has just switched, and the VPN is about to disconnect.
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006262 // Report that the VPN is not connected, so the state of NetworkInfo objects overwritten
6263 // by filterForLegacyLockdown will be set to CONNECTING and not CONNECTED.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006264 final NetworkAgentInfo defaultNetwork = getDefaultNetwork();
Lorenzo Colitti1f4db552021-02-12 10:14:01 +09006265 if (defaultNetwork == null || !defaultNetwork.network.equals(underlying[0])) {
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006266 return null;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006267 }
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006268
6269 return nai;
6270 };
6271
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006272 // TODO: move all callers to filterForLegacyLockdown and delete this method.
6273 // This likely requires making sendLegacyNetworkBroadcast take a NetworkInfo object instead of
6274 // just a DetailedState object.
Lorenzo Colittibcd692f2021-01-15 01:29:01 +09006275 private DetailedState getLegacyLockdownState(DetailedState origState) {
6276 if (origState != DetailedState.CONNECTED) {
6277 return origState;
6278 }
6279 return (mLockdownEnabled && getLegacyLockdownNai() == null)
6280 ? DetailedState.CONNECTING
6281 : DetailedState.CONNECTED;
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006282 }
6283
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09006284 private void filterForLegacyLockdown(NetworkInfo ni) {
6285 if (!mLockdownEnabled || !ni.isConnected()) return;
6286 // The legacy lockdown VPN replaces the state of every network in CONNECTED state with the
6287 // state of its VPN. This is to ensure that when an underlying network connects, apps will
6288 // not see a CONNECTIVITY_ACTION broadcast for a network in state CONNECTED until the VPN
6289 // comes up, at which point there is a new CONNECTIVITY_ACTION broadcast for the underlying
6290 // network, this time with a state of CONNECTED.
6291 //
6292 // Now that the legacy lockdown code lives in ConnectivityService, and no longer has access
6293 // to the internal state of the Vpn object, always replace the state with CONNECTING. This
6294 // is not too far off the truth, since an always-on VPN, when not connected, is always
6295 // trying to reconnect.
6296 if (getLegacyLockdownNai() == null) {
6297 ni.setDetailedState(DetailedState.CONNECTING, "", null);
6298 }
6299 }
6300
Pavel Grafov3aeb3f32019-01-25 08:50:06 +00006301 @Override
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006302 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensenebeaecd2014-09-15 15:59:36 -04006303 String action) {
paulhu8e96a752019-08-12 16:25:11 +08006304 enforceSettingsPermission();
Hugo Benichiad353f42017-06-20 14:07:59 +09006305 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
6306 return;
6307 }
Paul Jensenebeaecd2014-09-15 15:59:36 -04006308 final long ident = Binder.clearCallingIdentity();
6309 try {
Lorenzo Colittic5391022016-08-22 22:36:19 +09006310 // Concatenate the range of types onto the range of NetIDs.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09006311 int id = NetIdManager.MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittic5391022016-08-22 22:36:19 +09006312 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensenebeaecd2014-09-15 15:59:36 -04006313 } finally {
6314 Binder.restoreCallingIdentity(ident);
6315 }
Wink Saville9a1a7ef2013-08-29 08:55:16 -07006316 }
Wink Savillecb117d32013-08-29 14:57:08 -07006317
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006318 @Override
6319 public void setAirplaneMode(boolean enable) {
Edward Savage-Jonesd4723692019-11-26 13:18:08 +01006320 enforceAirplaneModePermission();
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006321 final long ident = Binder.clearCallingIdentity();
6322 try {
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006323 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichif4210292017-04-21 15:07:12 +09006324 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng239a3b22013-09-11 09:36:41 -07006325 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
6326 intent.putExtra("state", enable);
xinhe5598f9c2014-11-17 11:35:01 -08006327 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zhengb77f15d2013-09-09 17:00:04 -07006328 } finally {
6329 Binder.restoreCallingIdentity(ident);
6330 }
6331 }
6332
James Mattis02220e22021-03-13 19:27:21 -08006333 private void onUserAdded(@NonNull final UserHandle user) {
James Mattisae9aeb02021-03-01 17:09:11 -08006334 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6335 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6336 }
Chalard Jeane0abd522023-01-23 16:47:43 +09006337 updateProfileAllowedNetworks();
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006338 }
6339
James Mattis02220e22021-03-13 19:27:21 -08006340 private void onUserRemoved(@NonNull final UserHandle user) {
Chalard Jean0f57a492021-03-09 21:09:20 +09006341 // If there was a network preference for this user, remove it.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -08006342 handleSetProfileNetworkPreference(
Junyu Lai35665cc2022-12-19 17:37:48 +08006343 List.of(new ProfileNetworkPreferenceInfo(user, null, true,
6344 false /* blockingNonEnterprise */)),
Chalard Jean0f57a492021-03-09 21:09:20 +09006345 null /* listener */);
James Mattisae9aeb02021-03-01 17:09:11 -08006346 if (mOemNetworkPreferences.getNetworkPreferences().size() > 0) {
6347 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6348 }
junyulaid91e7052020-08-28 13:44:33 +08006349 }
6350
James Mattis02220e22021-03-13 19:27:21 -08006351 private void onPackageChanged(@NonNull final String packageName) {
6352 // This is necessary in case a package is added or removed, but also when it's replaced to
6353 // run as a new UID by its manifest rules. Also, if a separate package shares the same UID
6354 // as one in the preferences, then it should follow the same routing as that other package,
6355 // which means updating the rules is never to be needed in this case (whether it joins or
6356 // leaves a UID with a preference).
6357 if (isMappedInOemNetworkPreference(packageName)) {
6358 handleSetOemNetworkPreference(mOemNetworkPreferences, null);
6359 }
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006360
6361 // Invalidates cache entry when the package is updated.
6362 synchronized (mSelfCertifiedCapabilityCache) {
6363 mSelfCertifiedCapabilityCache.remove(packageName);
6364 }
James Mattis02220e22021-03-13 19:27:21 -08006365 }
6366
6367 private final BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006368 @Override
6369 public void onReceive(Context context, Intent intent) {
Lorenzo Colitti0fd959b2021-02-15 09:36:55 +09006370 ensureRunningOnConnectivityServiceThread();
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006371 final String action = intent.getAction();
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006372 final UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER);
junyulaid91e7052020-08-28 13:44:33 +08006373
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006374 // User should be filled for below intents, check the existence.
6375 if (user == null) {
6376 Log.wtf(TAG, intent.getAction() + " broadcast without EXTRA_USER");
6377 return;
6378 }
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006379
Lorenzo Colitticd675292021-02-04 17:32:07 +09006380 if (Intent.ACTION_USER_ADDED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006381 onUserAdded(user);
Fyodor Kupolov6c7a7802015-09-02 13:27:21 -07006382 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
Lorenzo Colitti8876a3d2021-02-16 15:42:21 +09006383 onUserRemoved(user);
Lorenzo Colitticd675292021-02-04 17:32:07 +09006384 } else {
junyulaid91e7052020-08-28 13:44:33 +08006385 Log.wtf(TAG, "received unexpected intent: " + action);
Chad Brubakerb7652cd2013-06-14 11:16:51 -07006386 }
6387 }
6388 };
Vinit Deshapnde30ad2542013-08-21 13:09:01 -07006389
James Mattis02220e22021-03-13 19:27:21 -08006390 private final BroadcastReceiver mPackageIntentReceiver = new BroadcastReceiver() {
6391 @Override
6392 public void onReceive(Context context, Intent intent) {
6393 ensureRunningOnConnectivityServiceThread();
6394 switch (intent.getAction()) {
6395 case Intent.ACTION_PACKAGE_ADDED:
6396 case Intent.ACTION_PACKAGE_REMOVED:
6397 case Intent.ACTION_PACKAGE_REPLACED:
6398 onPackageChanged(intent.getData().getSchemeSpecificPart());
6399 break;
6400 default:
6401 Log.wtf(TAG, "received unexpected intent: " + intent.getAction());
6402 }
6403 }
6404 };
6405
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006406 private final HashMap<Messenger, NetworkProviderInfo> mNetworkProviderInfos = new HashMap<>();
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006407 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests = new HashMap<>();
Robert Greenwalt7e45d112014-04-11 15:53:27 -07006408
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006409 private static class NetworkProviderInfo {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006410 public final String name;
6411 public final Messenger messenger;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006412 private final IBinder.DeathRecipient mDeathRecipient;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006413 public final int providerId;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006414
lifraf3a3492021-03-10 13:58:14 +08006415 NetworkProviderInfo(String name, Messenger messenger, int providerId,
6416 @NonNull IBinder.DeathRecipient deathRecipient) {
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006417 this.name = name;
6418 this.messenger = messenger;
Lorenzo Colittia86fae72020-01-10 00:40:28 +09006419 this.providerId = providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006420 mDeathRecipient = deathRecipient;
6421
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006422 if (mDeathRecipient == null) {
6423 throw new AssertionError("Must pass a deathRecipient");
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006424 }
6425 }
6426
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006427 void connect(Context context, Handler handler) {
Remi NGUYEN VAN2f7ba512021-02-04 18:04:43 +09006428 try {
6429 messenger.getBinder().linkToDeath(mDeathRecipient, 0);
6430 } catch (RemoteException e) {
6431 mDeathRecipient.binderDied();
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09006432 }
Lorenzo Colitti78185ea2020-01-07 19:36:24 +09006433 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006434 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006435
James Mattis4fce5d12020-11-12 15:53:42 -08006436 private void ensureAllNetworkRequestsHaveType(List<NetworkRequest> requests) {
6437 for (int i = 0; i < requests.size(); i++) {
6438 ensureNetworkRequestHasType(requests.get(i));
6439 }
6440 }
6441
Lorenzo Colitti70964d32016-07-05 01:22:13 +09006442 private void ensureNetworkRequestHasType(NetworkRequest request) {
6443 if (request.type == NetworkRequest.Type.NONE) {
6444 throw new IllegalArgumentException(
6445 "All NetworkRequests in ConnectivityService must have a type");
6446 }
6447 }
6448
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006449 /**
6450 * Tracks info about the requester.
James Mattisf7027322020-12-13 16:28:14 -08006451 * Also used to notice when the calling process dies so as to self-expire
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006452 */
James Mattis258ea3c2020-11-15 15:04:40 -08006453 @VisibleForTesting
6454 protected class NetworkRequestInfo implements IBinder.DeathRecipient {
James Mattise3ef1912020-12-20 11:09:58 -08006455 // The requests to be satisfied in priority order. Non-multilayer requests will only have a
6456 // single NetworkRequest in mRequests.
James Mattis60b84b22020-11-03 15:54:33 -08006457 final List<NetworkRequest> mRequests;
James Mattis60b84b22020-11-03 15:54:33 -08006458
James Mattisa076c532020-12-02 14:12:41 -08006459 // mSatisfier and mActiveRequest rely on one another therefore set them together.
6460 void setSatisfier(
6461 @Nullable final NetworkAgentInfo satisfier,
6462 @Nullable final NetworkRequest activeRequest) {
6463 mSatisfier = satisfier;
6464 mActiveRequest = activeRequest;
6465 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006466
James Mattisd31bdfa2020-12-23 16:37:26 -08006467 // The network currently satisfying this NRI. Only one request in an NRI can have a
Lorenzo Colitti96742d92021-01-29 20:18:03 +09006468 // satisfier. For non-multilayer requests, only non-listen requests can have a satisfier.
Chalard Jeandd8adb92019-11-05 15:07:09 +09006469 @Nullable
James Mattisa076c532020-12-02 14:12:41 -08006470 private NetworkAgentInfo mSatisfier;
6471 NetworkAgentInfo getSatisfier() {
6472 return mSatisfier;
6473 }
6474
6475 // The request in mRequests assigned to a network agent. This is null if none of the
6476 // requests in mRequests can be satisfied. This member has the constraint of only being
6477 // accessible on the handler thread.
6478 @Nullable
6479 private NetworkRequest mActiveRequest;
6480 NetworkRequest getActiveRequest() {
6481 return mActiveRequest;
6482 }
6483
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006484 final PendingIntent mPendingIntent;
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08006485 boolean mPendingIntentSent;
James Mattis45d81842021-01-10 14:24:24 -08006486 @Nullable
6487 final Messenger mMessenger;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006488
6489 // Information about the caller that caused this object to be created.
James Mattis45d81842021-01-10 14:24:24 -08006490 @Nullable
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006491 private final IBinder mBinder;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006492 final int mPid;
6493 final int mUid;
Roshan Pius951c0032020-12-22 15:10:42 -08006494 final @NetworkCallback.Flag int mCallbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006495 @Nullable
6496 final String mCallingAttributionTag;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006497
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006498 // Counter keeping track of this NRI.
Junyu Lai00d92df2022-07-05 11:01:52 +08006499 final RequestInfoPerUidCounter mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006500
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006501 // Effective UID of this request. This is different from mUid when a privileged process
6502 // files a request on behalf of another UID. This UID is used to determine blocked status,
6503 // UID matching, and so on. mUid above is used for permission checks and to enforce the
6504 // maximum limit of registered callbacks per UID.
6505 final int mAsUid;
6506
paulhu48291862021-07-14 14:53:57 +08006507 // Preference order of this request.
6508 final int mPreferenceOrder;
paulhue9913722021-05-26 15:19:20 +08006509
James Mattis3ce3d3c2021-02-09 18:18:28 -08006510 // In order to preserve the mapping of NetworkRequest-to-callback when apps register
6511 // callbacks using a returned NetworkRequest, the original NetworkRequest needs to be
6512 // maintained for keying off of. This is only a concern when the original nri
6513 // mNetworkRequests changes which happens currently for apps that register callbacks to
6514 // track the default network. In those cases, the nri is updated to have mNetworkRequests
6515 // that match the per-app default nri that currently tracks the calling app's uid so that
6516 // callbacks are fired at the appropriate time. When the callbacks fire,
6517 // mNetworkRequestForCallback will be used so as to preserve the caller's mapping. When
6518 // callbacks are updated to key off of an nri vs NetworkRequest, this stops being an issue.
6519 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
6520 @NonNull
6521 private final NetworkRequest mNetworkRequestForCallback;
6522 NetworkRequest getNetworkRequestForCallback() {
6523 return mNetworkRequestForCallback;
6524 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006525
James Mattisd31bdfa2020-12-23 16:37:26 -08006526 /**
6527 * Get the list of UIDs this nri applies to.
6528 */
6529 @NonNull
paulhu51f77dc2021-06-07 02:34:20 +00006530 Set<UidRange> getUids() {
James Mattisd31bdfa2020-12-23 16:37:26 -08006531 // networkCapabilities.getUids() returns a defensive copy.
6532 // multilayer requests will all have the same uids so return the first one.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00006533 final Set<UidRange> uids = mRequests.get(0).networkCapabilities.getUidRanges();
6534 return (null == uids) ? new ArraySet<>() : uids;
James Mattisd31bdfa2020-12-23 16:37:26 -08006535 }
6536
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006537 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r,
6538 @Nullable final PendingIntent pi, @Nullable String callingAttributionTag) {
paulhue9913722021-05-26 15:19:20 +08006539 this(asUid, Collections.singletonList(r), r, pi, callingAttributionTag,
paulhu48291862021-07-14 14:53:57 +08006540 PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006541 }
6542
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006543 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006544 @NonNull final NetworkRequest requestForCallback, @Nullable final PendingIntent pi,
paulhu48291862021-07-14 14:53:57 +08006545 @Nullable String callingAttributionTag, final int preferenceOrder) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08006546 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006547 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006548 mNetworkRequestForCallback = requestForCallback;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006549 mPendingIntent = pi;
James Mattis45d81842021-01-10 14:24:24 -08006550 mMessenger = null;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006551 mBinder = null;
6552 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006553 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006554 mAsUid = asUid;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006555 mPerUidCounter = getRequestCounter(this);
6556 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006557 /**
6558 * Location sensitive data not included in pending intent. Only included in
6559 * {@link NetworkCallback}.
6560 */
6561 mCallbackFlags = NetworkCallback.FLAG_NONE;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006562 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006563 mPreferenceOrder = preferenceOrder;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006564 }
6565
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006566 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006567 @Nullable final IBinder binder,
6568 @NetworkCallback.Flag int callbackFlags,
6569 @Nullable String callingAttributionTag) {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006570 this(asUid, Collections.singletonList(r), r, m, binder, callbackFlags,
6571 callingAttributionTag);
James Mattis45d81842021-01-10 14:24:24 -08006572 }
6573
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006574 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006575 @NonNull final NetworkRequest requestForCallback, @Nullable final Messenger m,
Roshan Pius951c0032020-12-22 15:10:42 -08006576 @Nullable final IBinder binder,
6577 @NetworkCallback.Flag int callbackFlags,
6578 @Nullable String callingAttributionTag) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006579 super();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006580 ensureAllNetworkRequestsHaveType(r);
James Mattis60b84b22020-11-03 15:54:33 -08006581 mRequests = initializeRequests(r);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006582 mNetworkRequestForCallback = requestForCallback;
James Mattis45d81842021-01-10 14:24:24 -08006583 mMessenger = m;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006584 mBinder = binder;
6585 mPid = getCallingPid();
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006586 mUid = mDeps.getCallingUid();
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006587 mAsUid = asUid;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006588 mPendingIntent = null;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006589 mPerUidCounter = getRequestCounter(this);
6590 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006591 mCallbackFlags = callbackFlags;
Roshan Piusaa24fde2020-12-17 14:53:09 -08006592 mCallingAttributionTag = callingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006593 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006594 linkDeathRecipient();
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006595 }
6596
James Mattis3ce3d3c2021-02-09 18:18:28 -08006597 NetworkRequestInfo(@NonNull final NetworkRequestInfo nri,
6598 @NonNull final List<NetworkRequest> r) {
6599 super();
6600 ensureAllNetworkRequestsHaveType(r);
6601 mRequests = initializeRequests(r);
6602 mNetworkRequestForCallback = nri.getNetworkRequestForCallback();
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006603 final NetworkAgentInfo satisfier = nri.getSatisfier();
6604 if (null != satisfier) {
6605 // If the old NRI was satisfied by an NAI, then it may have had an active request.
6606 // The active request is necessary to figure out what callbacks to send, in
Chalard Jean2ddcf602022-02-27 12:16:32 +09006607 // particular when a network updates its capabilities.
Chalard Jeanb5becbc2021-03-05 19:18:14 +09006608 // As this code creates a new NRI with a new set of requests, figure out which of
6609 // the list of requests should be the active request. It is always the first
6610 // request of the list that can be satisfied by the satisfier since the order of
6611 // requests is a priority order.
6612 // Note even in the presence of a satisfier there may not be an active request,
6613 // when the satisfier is the no-service network.
6614 NetworkRequest activeRequest = null;
6615 for (final NetworkRequest candidate : r) {
6616 if (candidate.canBeSatisfiedBy(satisfier.networkCapabilities)) {
6617 activeRequest = candidate;
6618 break;
6619 }
6620 }
6621 setSatisfier(satisfier, activeRequest);
6622 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08006623 mMessenger = nri.mMessenger;
6624 mBinder = nri.mBinder;
6625 mPid = nri.mPid;
6626 mUid = nri.mUid;
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006627 mAsUid = nri.mAsUid;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006628 mPendingIntent = nri.mPendingIntent;
Chalard Jean9473c982021-07-29 20:03:04 +09006629 mPerUidCounter = nri.mPerUidCounter;
Chalard Jeanefbfd7f2021-04-01 16:41:04 +09006630 mPerUidCounter.incrementCountOrThrow(mUid);
Roshan Pius951c0032020-12-22 15:10:42 -08006631 mCallbackFlags = nri.mCallbackFlags;
James Mattis3ce3d3c2021-02-09 18:18:28 -08006632 mCallingAttributionTag = nri.mCallingAttributionTag;
paulhu48291862021-07-14 14:53:57 +08006633 mPreferenceOrder = PREFERENCE_ORDER_INVALID;
James Mattisb1392002021-03-31 13:57:52 -07006634 linkDeathRecipient();
James Mattis3ce3d3c2021-02-09 18:18:28 -08006635 }
6636
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006637 NetworkRequestInfo(int asUid, @NonNull final NetworkRequest r) {
paulhu48291862021-07-14 14:53:57 +08006638 this(asUid, Collections.singletonList(r), PREFERENCE_ORDER_INVALID);
James Mattis45d81842021-01-10 14:24:24 -08006639 }
6640
paulhue9913722021-05-26 15:19:20 +08006641 NetworkRequestInfo(int asUid, @NonNull final List<NetworkRequest> r,
paulhu48291862021-07-14 14:53:57 +08006642 final int preferenceOrder) {
paulhue9913722021-05-26 15:19:20 +08006643 this(asUid, r, r.get(0), null /* pi */, null /* callingAttributionTag */,
paulhu48291862021-07-14 14:53:57 +08006644 preferenceOrder);
Cody Kesting73708bf2019-12-18 10:57:50 -08006645 }
6646
James Mattis2516da32021-01-31 17:06:19 -08006647 // True if this NRI is being satisfied. It also accounts for if the nri has its satisifer
6648 // set to the mNoServiceNetwork in which case mActiveRequest will be null thus returning
6649 // false.
6650 boolean isBeingSatisfied() {
6651 return (null != mSatisfier && null != mActiveRequest);
6652 }
6653
James Mattis3d229892020-11-16 16:46:28 -08006654 boolean isMultilayerRequest() {
6655 return mRequests.size() > 1;
6656 }
6657
James Mattis45d81842021-01-10 14:24:24 -08006658 private List<NetworkRequest> initializeRequests(List<NetworkRequest> r) {
6659 // Creating a defensive copy to prevent the sender from modifying the list being
6660 // reflected in the return value of this method.
6661 final List<NetworkRequest> tempRequests = new ArrayList<>(r);
James Mattis60b84b22020-11-03 15:54:33 -08006662 return Collections.unmodifiableList(tempRequests);
6663 }
6664
James Mattisb1392002021-03-31 13:57:52 -07006665 void linkDeathRecipient() {
6666 if (null != mBinder) {
6667 try {
6668 mBinder.linkToDeath(this, 0);
6669 } catch (RemoteException e) {
6670 binderDied();
6671 }
6672 }
6673 }
6674
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006675 void unlinkDeathRecipient() {
James Mattisb1392002021-03-31 13:57:52 -07006676 if (null != mBinder) {
Chalard Jean524f0b12021-10-25 21:11:56 +09006677 try {
6678 mBinder.unlinkToDeath(this, 0);
6679 } catch (NoSuchElementException e) {
6680 // Temporary workaround for b/194394697 pending analysis of additional logs
6681 Log.wtf(TAG, "unlinkToDeath for already unlinked NRI " + this);
6682 }
Jeremy Joslin60d379b2014-11-05 10:32:09 -08006683 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006684 }
6685
paulhu48291862021-07-14 14:53:57 +08006686 boolean hasHigherOrderThan(@NonNull final NetworkRequestInfo target) {
6687 // Compare two preference orders.
6688 return mPreferenceOrder < target.mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006689 }
6690
paulhu48291862021-07-14 14:53:57 +08006691 int getPreferenceOrderForNetd() {
6692 if (mPreferenceOrder >= PREFERENCE_ORDER_NONE
6693 && mPreferenceOrder <= PREFERENCE_ORDER_LOWEST) {
6694 return mPreferenceOrder;
paulhuaa0743d2021-05-26 21:56:03 +08006695 }
paulhu48291862021-07-14 14:53:57 +08006696 return PREFERENCE_ORDER_NONE;
paulhuaa0743d2021-05-26 21:56:03 +08006697 }
6698
James Mattis4fce5d12020-11-12 15:53:42 -08006699 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006700 public void binderDied() {
Chalard Jean5bcc8382021-07-19 19:57:02 +09006701 // As an immutable collection, mRequests cannot change by the time the
6702 // lambda is evaluated on the handler thread so calling .get() from a binder thread
6703 // is acceptable. Use handleReleaseNetworkRequest and not directly
6704 // handleRemoveNetworkRequest so as to force a lookup in the requests map, in case
6705 // the app already unregistered the request.
6706 mHandler.post(() -> handleReleaseNetworkRequest(mRequests.get(0),
6707 mUid, false /* callOnUnavailable */));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006708 }
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006709
James Mattis4fce5d12020-11-12 15:53:42 -08006710 @Override
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006711 public String toString() {
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006712 final String asUidString = (mAsUid == mUid) ? "" : " asUid: " + mAsUid;
6713 return "uid/pid:" + mUid + "/" + mPid + asUidString + " activeRequest: "
James Mattisd31bdfa2020-12-23 16:37:26 -08006714 + (mActiveRequest == null ? null : mActiveRequest.requestId)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006715 + " callbackRequest: "
Chalard Jean5d6e23b2021-03-01 22:00:20 +09006716 + mNetworkRequestForCallback.requestId
James Mattisd31bdfa2020-12-23 16:37:26 -08006717 + " " + mRequests
Roshan Pius951c0032020-12-22 15:10:42 -08006718 + (mPendingIntent == null ? "" : " to trigger " + mPendingIntent)
paulhuaa0743d2021-05-26 21:56:03 +08006719 + " callback flags: " + mCallbackFlags
paulhu48291862021-07-14 14:53:57 +08006720 + " order: " + mPreferenceOrder;
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07006721 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006722 }
6723
Junyu Lai00d92df2022-07-05 11:01:52 +08006724 // Keep backward compatibility since the ServiceSpecificException is used by
6725 // the API surface, see {@link ConnectivityManager#convertServiceException}.
6726 public static class RequestInfoPerUidCounter extends PerUidCounter {
6727 RequestInfoPerUidCounter(int maxCountPerUid) {
6728 super(maxCountPerUid);
6729 }
6730
6731 @Override
6732 public synchronized void incrementCountOrThrow(int uid) {
6733 try {
6734 super.incrementCountOrThrow(uid);
6735 } catch (IllegalStateException e) {
6736 throw new ServiceSpecificException(
6737 ConnectivityManager.Errors.TOO_MANY_REQUESTS,
6738 "Uid " + uid + " exceeded its allotted requests limit");
6739 }
6740 }
6741
6742 @Override
6743 public synchronized void decrementCountOrThrow(int uid) {
6744 throw new UnsupportedOperationException("Use decrementCount instead.");
6745 }
6746
6747 public synchronized void decrementCount(int uid) {
6748 try {
6749 super.decrementCountOrThrow(uid);
6750 } catch (IllegalStateException e) {
6751 logwtf("Exception when decrement per uid request count: ", e);
6752 }
6753 }
6754 }
6755
Chalard Jeanfbab6d42019-09-26 18:03:47 +09006756 // This checks that the passed capabilities either do not request a
6757 // specific SSID/SignalStrength, or the calling app has permission to do so.
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006758 private void ensureSufficientPermissionsForRequest(NetworkCapabilities nc,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006759 int callerPid, int callerUid, String callerPackageName) {
Chalard Jean542e6002020-03-18 15:58:50 +09006760 if (null != nc.getSsid() && !checkSettingsPermission(callerPid, callerUid)) {
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006761 throw new SecurityException("Insufficient permissions to request a specific SSID");
6762 }
paulhu1a407652019-03-22 16:35:06 +08006763
6764 if (nc.hasSignalStrength()
6765 && !checkNetworkSignalStrengthWakeupPermission(callerPid, callerUid)) {
6766 throw new SecurityException(
6767 "Insufficient permissions to request a specific signal strength");
6768 }
Roshan Pius08c94fb2020-01-16 12:17:17 -08006769 mAppOpsManager.checkPackage(callerUid, callerPackageName);
Benedict Wong53de25f2021-03-24 14:01:51 -07006770
junyulai2217bec2021-04-14 23:33:31 +08006771 if (!nc.getSubscriptionIds().isEmpty()) {
Benedict Wong53de25f2021-03-24 14:01:51 -07006772 enforceNetworkFactoryPermission();
6773 }
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006774 }
6775
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006776 private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09006777 final SortedSet<Integer> thresholds = new TreeSet<>();
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006778 synchronized (nai) {
James Mattisa076c532020-12-02 14:12:41 -08006779 // mNetworkRequests may contain the same value multiple times in case of
6780 // multilayer requests. It won't matter in this case because the thresholds
6781 // will then be the same and be deduplicated as they enter the `thresholds` set.
6782 // TODO : have mNetworkRequests be a Set<NetworkRequestInfo> or the like.
James Mattisd951eec2020-11-18 16:23:25 -08006783 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
6784 for (final NetworkRequest req : nri.mRequests) {
6785 if (req.networkCapabilities.hasSignalStrength()
6786 && nai.satisfiesImmutableCapabilitiesOf(req)) {
6787 thresholds.add(req.networkCapabilities.getSignalStrength());
6788 }
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006789 }
6790 }
6791 }
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09006792 return CollectionUtils.toIntArray(new ArrayList<>(thresholds));
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006793 }
6794
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006795 private void updateSignalStrengthThresholds(
6796 NetworkAgentInfo nai, String reason, NetworkRequest request) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006797 final int[] thresholdsArray = getSignalStrengthThresholds(nai);
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006798
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09006799 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006800 String detail;
6801 if (request != null && request.networkCapabilities.hasSignalStrength()) {
6802 detail = reason + " " + request.networkCapabilities.getSignalStrength();
6803 } else {
6804 detail = reason;
6805 }
6806 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006807 detail, Arrays.toString(thresholdsArray), nai.toShortString()));
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09006808 }
6809
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09006810 nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09006811 }
6812
Chalard Jeandd421992021-12-16 23:16:02 +09006813 private static void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
Etan Cohen1b6d4182017-04-03 17:42:34 -07006814 if (nc == null) {
6815 return;
6816 }
6817 NetworkSpecifier ns = nc.getNetworkSpecifier();
6818 if (ns == null) {
6819 return;
6820 }
lucaslin22f9b9f2021-01-22 15:15:23 +08006821 if (ns instanceof MatchAllNetworkSpecifier) {
6822 throw new IllegalArgumentException("A MatchAllNetworkSpecifier is not permitted");
6823 }
Etan Cohen1b6d4182017-04-03 17:42:34 -07006824 }
6825
Chalard Jeandd421992021-12-16 23:16:02 +09006826 private static void ensureListenableCapabilities(@NonNull final NetworkCapabilities nc) {
lucasline117e2e2019-10-22 18:27:33 +08006827 ensureValidNetworkSpecifier(nc);
6828 if (nc.isPrivateDnsBroken()) {
6829 throw new IllegalArgumentException("Can't request broken private DNS");
6830 }
Chalard Jeande665262022-02-25 16:12:12 +09006831 if (nc.hasAllowedUids()) {
Chalard Jean9a30acf2021-12-13 22:53:51 +09006832 throw new IllegalArgumentException("Can't request access UIDs");
6833 }
lucasline117e2e2019-10-22 18:27:33 +08006834 }
6835
Chalard Jeandd421992021-12-16 23:16:02 +09006836 private void ensureRequestableCapabilities(@NonNull final NetworkCapabilities nc) {
6837 ensureListenableCapabilities(nc);
6838 final String badCapability = nc.describeFirstNonRequestableCapability();
6839 if (badCapability != null) {
6840 throw new IllegalArgumentException("Cannot request network with " + badCapability);
6841 }
6842 }
6843
Chiachang Wang3bc52762021-11-25 14:17:57 +08006844 // TODO: Set the mini sdk to 31 and remove @TargetApi annotation when b/205923322 is addressed.
6845 @TargetApi(Build.VERSION_CODES.S)
Roshan Pius951c0032020-12-22 15:10:42 -08006846 private boolean isTargetSdkAtleast(int version, int callingUid,
6847 @NonNull String callingPackageName) {
6848 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
paulhu310c9fb2020-12-10 23:32:32 +08006849 final PackageManager pm =
6850 mContext.createContextAsUser(user, 0 /* flags */).getPackageManager();
markchien9eb93992020-03-27 18:12:39 +08006851 try {
Roshan Pius951c0032020-12-22 15:10:42 -08006852 final int callingVersion = pm.getTargetSdkVersion(callingPackageName);
markchien9eb93992020-03-27 18:12:39 +08006853 if (callingVersion < version) return false;
6854 } catch (PackageManager.NameNotFoundException e) { }
6855 return true;
6856 }
6857
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006858 @Override
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006859 public NetworkRequest requestNetwork(int asUid, NetworkCapabilities networkCapabilities,
Chalard Jeana3578a52021-10-25 19:24:48 +09006860 int reqTypeInt, Messenger messenger, int timeoutMs, final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006861 int legacyType, int callbackFlags, @NonNull String callingPackageName,
junyulaiad010792021-01-11 16:53:38 +08006862 @Nullable String callingAttributionTag) {
markchienfac84a22020-03-18 21:16:15 +08006863 if (legacyType != TYPE_NONE && !checkNetworkStackPermission()) {
Roshan Pius951c0032020-12-22 15:10:42 -08006864 if (isTargetSdkAtleast(Build.VERSION_CODES.M, mDeps.getCallingUid(),
6865 callingPackageName)) {
markchien9eb93992020-03-27 18:12:39 +08006866 throw new SecurityException("Insufficient permissions to specify legacy type");
6867 }
markchienfac84a22020-03-18 21:16:15 +08006868 }
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006869 final NetworkCapabilities defaultNc = mDefaultRequest.mRequests.get(0).networkCapabilities;
Lorenzo Colittif61ca942020-12-15 11:02:22 +09006870 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006871 // Privileged callers can track the default network of another UID by passing in a UID.
6872 if (asUid != Process.INVALID_UID) {
6873 enforceSettingsPermission();
6874 } else {
6875 asUid = callingUid;
6876 }
junyulaiad010792021-01-11 16:53:38 +08006877 final NetworkRequest.Type reqType;
6878 try {
6879 reqType = NetworkRequest.Type.values()[reqTypeInt];
6880 } catch (ArrayIndexOutOfBoundsException e) {
6881 throw new IllegalArgumentException("Unsupported request type " + reqTypeInt);
6882 }
6883 switch (reqType) {
6884 case TRACK_DEFAULT:
6885 // If the request type is TRACK_DEFAULT, the passed {@code networkCapabilities}
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006886 // is unused and will be replaced by ones appropriate for the UID (usually, the
6887 // calling app). This allows callers to keep track of the default network.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006888 networkCapabilities = copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006889 defaultNc, asUid, callingUid, callingPackageName);
junyulaiad010792021-01-11 16:53:38 +08006890 enforceAccessPermission();
6891 break;
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006892 case TRACK_SYSTEM_DEFAULT:
Quang Luong98858d62023-02-11 00:25:24 +00006893 enforceSettingsOrSetupWizardOrUseRestrictedNetworksPermission();
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006894 networkCapabilities = new NetworkCapabilities(defaultNc);
6895 break;
Junyu Laia62493f2021-01-19 11:10:56 +00006896 case BACKGROUND_REQUEST:
6897 enforceNetworkStackOrSettingsPermission();
6898 // Fall-through since other checks are the same with normal requests.
junyulaiad010792021-01-11 16:53:38 +08006899 case REQUEST:
6900 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6901 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08006902 callingAttributionTag, callingUid);
junyulaiad010792021-01-11 16:53:38 +08006903 // TODO: this is incorrect. We mark the request as metered or not depending on
6904 // the state of the app when the request is filed, but we never change the
6905 // request if the app changes network state. http://b/29964605
6906 enforceMeteredApnPolicy(networkCapabilities);
6907 break;
junyulai1b1c8742021-03-12 20:05:08 +08006908 case LISTEN_FOR_BEST:
6909 enforceAccessPermission();
6910 networkCapabilities = new NetworkCapabilities(networkCapabilities);
6911 break;
junyulaiad010792021-01-11 16:53:38 +08006912 default:
6913 throw new IllegalArgumentException("Unsupported request type " + reqType);
Erik Kline23bf99c2016-03-16 15:31:39 +09006914 }
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09006915 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09006916 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08006917 Binder.getCallingPid(), callingUid, callingPackageName);
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006918
junyulai1b1c8742021-03-12 20:05:08 +08006919 // Enforce FOREGROUND if the caller does not have permission to use background network.
6920 if (reqType == LISTEN_FOR_BEST) {
6921 restrictBackgroundRequestForCaller(networkCapabilities);
6922 }
6923
6924 // Set the UID range for this request to the single UID of the requester, unless the
6925 // requester has the permission to specify other UIDs.
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09006926 // This will overwrite any allowed UIDs in the requested capabilities. Though there
6927 // are no visible methods to set the UIDs, an app could use reflection to try and get
6928 // networks for other apps so it's essential that the UIDs are overwritten.
junyulai1b1c8742021-03-12 20:05:08 +08006929 // Also set the requester UID and package name in the request.
Roshan Pius08c94fb2020-01-16 12:17:17 -08006930 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
6931 callingUid, callingPackageName);
Robert Greenwaltc36a74f2014-07-27 10:56:49 -07006932
Etan Cohen85000162017-02-05 10:42:27 -08006933 if (timeoutMs < 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006934 throw new IllegalArgumentException("Bad timeout specified");
6935 }
Etan Cohen9786d922015-11-18 10:56:15 -08006936
James Mattis3ce3d3c2021-02-09 18:18:28 -08006937 final NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
junyulaiad010792021-01-11 16:53:38 +08006938 nextNetworkRequestId(), reqType);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006939 final NetworkRequestInfo nri = getNriToRegister(
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +09006940 asUid, networkRequest, messenger, binder, callbackFlags,
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006941 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09006942 if (DBG) log("requestNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006943
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006944 // For TRACK_SYSTEM_DEFAULT callbacks, the capabilities have been modified since they were
6945 // copied from the default request above. (This is necessary to ensure, for example, that
6946 // the callback does not leak sensitive information to unprivileged apps.) Check that the
6947 // changes don't alter request matching.
6948 if (reqType == NetworkRequest.Type.TRACK_SYSTEM_DEFAULT &&
6949 (!networkCapabilities.equalRequestableCapabilities(defaultNc))) {
Lorenzo Colitti4777edc2021-02-10 11:59:07 +09006950 throw new IllegalStateException(
6951 "TRACK_SYSTEM_DEFAULT capabilities don't match default request: "
Lorenzo Colitti76b639e2021-01-29 20:14:04 +09006952 + networkCapabilities + " vs. " + defaultNc);
6953 }
6954
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006955 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006956 if (timeoutMs > 0) {
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006957 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwaltf57c03c2014-06-11 16:05:07 -07006958 nri), timeoutMs);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07006959 }
6960 return networkRequest;
6961 }
6962
James Mattis3ce3d3c2021-02-09 18:18:28 -08006963 /**
6964 * Return the nri to be used when registering a network request. Specifically, this is used with
6965 * requests registered to track the default request. If there is currently a per-app default
6966 * tracking the app requestor, then we need to create a version of this nri that mirrors that of
6967 * the tracking per-app default so that callbacks are sent to the app requestor appropriately.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006968 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
6969 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08006970 * @param nr the network request for the nri.
6971 * @param msgr the messenger for the nri.
6972 * @param binder the binder for the nri.
6973 * @param callingAttributionTag the calling attribution tag for the nri.
6974 * @return the nri to register.
6975 */
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006976 private NetworkRequestInfo getNriToRegister(final int asUid, @NonNull final NetworkRequest nr,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006977 @Nullable final Messenger msgr, @Nullable final IBinder binder,
Roshan Pius951c0032020-12-22 15:10:42 -08006978 @NetworkCallback.Flag int callbackFlags,
James Mattis3ce3d3c2021-02-09 18:18:28 -08006979 @Nullable String callingAttributionTag) {
6980 final List<NetworkRequest> requests;
6981 if (NetworkRequest.Type.TRACK_DEFAULT == nr.type) {
6982 requests = copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006983 asUid, nr.getRequestorUid(), nr.getRequestorPackageName());
James Mattis3ce3d3c2021-02-09 18:18:28 -08006984 } else {
6985 requests = Collections.singletonList(nr);
6986 }
Roshan Pius951c0032020-12-22 15:10:42 -08006987 return new NetworkRequestInfo(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09006988 asUid, requests, nr, msgr, binder, callbackFlags, callingAttributionTag);
James Mattis3ce3d3c2021-02-09 18:18:28 -08006989 }
6990
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09006991 private boolean shouldCheckCapabilitiesDeclaration(
6992 @NonNull final NetworkCapabilities networkCapabilities, final int callingUid,
6993 @NonNull final String callingPackageName) {
6994 final UserHandle user = UserHandle.getUserHandleForUid(callingUid);
6995 // Only run the check if the change is enabled.
6996 if (!mDeps.isChangeEnabled(
6997 ConnectivityCompatChanges.ENABLE_SELF_CERTIFIED_CAPABILITIES_DECLARATION,
6998 callingPackageName, user)) {
6999 return false;
7000 }
7001
7002 return networkCapabilities.hasCapability(
7003 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH)
7004 || networkCapabilities.hasCapability(
7005 NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY);
7006 }
7007
7008 private void enforceRequestCapabilitiesDeclaration(@NonNull final String callerPackageName,
7009 @NonNull final NetworkCapabilities networkCapabilities) {
7010 // This check is added to fix the linter error for "current min is 30", which is not going
7011 // to happen because Connectivity service always run in S+.
7012 if (!SdkLevel.isAtLeastS()) {
7013 Log.wtf(TAG, "Connectivity service should always run in at least SDK S");
7014 return;
7015 }
7016 ApplicationSelfCertifiedNetworkCapabilities applicationNetworkCapabilities;
Yuyang Huang2d13d432023-03-13 12:27:40 +09007017 final long ident = Binder.clearCallingIdentity();
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007018 try {
7019 synchronized (mSelfCertifiedCapabilityCache) {
7020 applicationNetworkCapabilities = mSelfCertifiedCapabilityCache.get(
7021 callerPackageName);
7022 if (applicationNetworkCapabilities == null) {
7023 final PackageManager packageManager = mContext.getPackageManager();
7024 final PackageManager.Property networkSliceProperty = packageManager.getProperty(
7025 ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES,
7026 callerPackageName
7027 );
7028 final XmlResourceParser parser = packageManager
7029 .getResourcesForApplication(callerPackageName)
7030 .getXml(networkSliceProperty.getResourceId());
7031 applicationNetworkCapabilities =
7032 ApplicationSelfCertifiedNetworkCapabilities.createFromXml(parser);
7033 mSelfCertifiedCapabilityCache.put(callerPackageName,
7034 applicationNetworkCapabilities);
7035 }
7036
7037 }
7038 } catch (PackageManager.NameNotFoundException ne) {
7039 throw new SecurityException(
7040 "Cannot find " + ConstantsShim.PROPERTY_SELF_CERTIFIED_NETWORK_CAPABILITIES
7041 + " property");
7042 } catch (XmlPullParserException | IOException | InvalidTagException e) {
7043 throw new SecurityException(e.getMessage());
Yuyang Huang2d13d432023-03-13 12:27:40 +09007044 } finally {
7045 Binder.restoreCallingIdentity(ident);
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007046 }
7047
7048 applicationNetworkCapabilities.enforceSelfCertifiedNetworkCapabilitiesDeclared(
7049 networkCapabilities);
7050 }
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007051 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities,
junyulai96bd9fe2022-03-08 17:36:42 +08007052 String callingPackageName, String callingAttributionTag, final int callingUid) {
Yuyang Huang96e8bfe2023-01-27 17:05:07 +09007053 if (shouldCheckCapabilitiesDeclaration(networkCapabilities, callingUid,
7054 callingPackageName)) {
7055 enforceRequestCapabilitiesDeclaration(callingPackageName, networkCapabilities);
7056 }
Lorenzo Colittie97685a2015-05-14 17:28:27 +09007057 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
junyulai96bd9fe2022-03-08 17:36:42 +08007058 // For T+ devices, callers with carrier privilege could request with CBS capabilities.
7059 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_CBS)
7060 && hasCarrierPrivilegeForNetworkCaps(callingUid, networkCapabilities)) {
7061 return;
Sooraj Sasindrane9cd2082022-01-13 15:46:52 -08007062 }
junyulai96bd9fe2022-03-08 17:36:42 +08007063 enforceConnectivityRestrictedNetworksPermission(true /* checkUidsAllowedList */);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007064 } else {
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007065 enforceChangePermission(callingPackageName, callingAttributionTag);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007066 }
7067 }
7068
fenglu3f357402015-03-20 11:29:56 -07007069 @Override
fenglub00f4882015-04-21 17:12:05 -07007070 public boolean requestBandwidthUpdate(Network network) {
fenglu3f357402015-03-20 11:29:56 -07007071 enforceAccessPermission();
7072 NetworkAgentInfo nai = null;
7073 if (network == null) {
7074 return false;
7075 }
7076 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007077 nai = mNetworkForNetId.get(network.getNetId());
fenglu3f357402015-03-20 11:29:56 -07007078 }
7079 if (nai != null) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007080 nai.onBandwidthUpdateRequested();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007081 synchronized (mBandwidthRequests) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007082 final int uid = mDeps.getCallingUid();
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007083 Integer uidReqs = mBandwidthRequests.get(uid);
7084 if (uidReqs == null) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09007085 uidReqs = 0;
Nathan Haroldb89cbfb2018-07-30 13:38:01 -07007086 }
7087 mBandwidthRequests.put(uid, ++uidReqs);
7088 }
fenglu3f357402015-03-20 11:29:56 -07007089 return true;
7090 }
7091 return false;
7092 }
7093
Felipe Leme0a5ae422016-06-20 16:36:29 -07007094 private boolean isSystem(int uid) {
7095 return uid < Process.FIRST_APPLICATION_UID;
7096 }
fenglu3f357402015-03-20 11:29:56 -07007097
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007098 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007099 final int uid = mDeps.getCallingUid();
Felipe Leme0a5ae422016-06-20 16:36:29 -07007100 if (isSystem(uid)) {
Hugo Benichi39621362017-02-11 17:04:43 +09007101 // Exemption for system uid.
Felipe Leme0a5ae422016-06-20 16:36:29 -07007102 return;
7103 }
Hugo Benichi39621362017-02-11 17:04:43 +09007104 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
7105 // Policy already enforced.
7106 return;
7107 }
paulhuaf50d7d2020-12-24 19:47:34 +08007108 final long ident = Binder.clearCallingIdentity();
7109 try {
7110 if (mPolicyManager.isUidRestrictedOnMeteredNetworks(uid)) {
7111 // If UID is restricted, don't allow them to bring up metered APNs.
7112 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
7113 }
7114 } finally {
7115 Binder.restoreCallingIdentity(ident);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007116 }
7117 }
7118
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007119 @Override
7120 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007121 PendingIntent operation, @NonNull String callingPackageName,
7122 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007123 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007124 final int callingUid = mDeps.getCallingUid();
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007125 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Philip P. Moltmann7bc33df2020-03-26 11:50:35 -07007126 enforceNetworkRequestPermissions(networkCapabilities, callingPackageName,
junyulai96bd9fe2022-03-08 17:36:42 +08007127 callingAttributionTag, callingUid);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007128 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti6b56e9e2015-07-08 12:49:04 +09007129 ensureRequestableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007130 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007131 Binder.getCallingPid(), callingUid, callingPackageName);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007132 restrictRequestUidsForCallerAndSetRequestorInfo(networkCapabilities,
7133 callingUid, callingPackageName);
Chalard Jean15228572022-01-28 19:29:12 +09007134
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007135 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007136 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007137 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7138 callingAttributionTag);
Erik Klineedf878b2015-07-09 18:24:03 +09007139 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007140 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
7141 nri));
7142 return networkRequest;
7143 }
7144
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007145 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
7146 mHandler.sendMessageDelayed(
7147 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007148 mDeps.getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08007149 }
7150
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007151 @Override
7152 public void releasePendingNetworkRequest(PendingIntent operation) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007153 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin60d379b2014-11-05 10:32:09 -08007154 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007155 mDeps.getCallingUid(), 0, operation));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007156 }
7157
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007158 // In order to implement the compatibility measure for pre-M apps that call
7159 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
7160 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
7161 // This ensures it has permission to do so.
7162 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
7163 if (nc == null) {
7164 return false;
7165 }
7166 int[] transportTypes = nc.getTransportTypes();
7167 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
7168 return false;
7169 }
7170 try {
7171 mContext.enforceCallingOrSelfPermission(
7172 android.Manifest.permission.ACCESS_WIFI_STATE,
7173 "ConnectivityService");
7174 } catch (SecurityException e) {
7175 return false;
7176 }
7177 return true;
7178 }
7179
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007180 @Override
7181 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Pius951c0032020-12-22 15:10:42 -08007182 Messenger messenger, IBinder binder,
7183 @NetworkCallback.Flag int callbackFlags,
7184 @NonNull String callingPackageName, @NonNull String callingAttributionTag) {
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007185 final int callingUid = mDeps.getCallingUid();
Lorenzo Colitti7e7decd2015-04-22 10:44:49 +09007186 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7187 enforceAccessPermission();
7188 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007189
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007190 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007191 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007192 Binder.getCallingPid(), callingUid, callingPackageName);
7193 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jean38354d12018-03-20 19:13:57 +09007194 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
7195 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
7196 // onLost and onAvailable callbacks when networks move in and out of the background.
7197 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
7198 // can't request networks.
7199 restrictBackgroundRequestForCaller(nc);
Chalard Jeandd421992021-12-16 23:16:02 +09007200 ensureListenableCapabilities(nc);
Etan Cohen89134542017-04-03 12:17:51 -07007201
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09007202 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007203 NetworkRequest.Type.LISTEN);
Roshan Piusaa24fde2020-12-17 14:53:09 -08007204 NetworkRequestInfo nri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007205 new NetworkRequestInfo(callingUid, networkRequest, messenger, binder, callbackFlags,
Roshan Pius951c0032020-12-22 15:10:42 -08007206 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007207 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007208
7209 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
7210 return networkRequest;
7211 }
7212
7213 @Override
7214 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
Roshan Piusaa24fde2020-12-17 14:53:09 -08007215 PendingIntent operation, @NonNull String callingPackageName,
7216 @Nullable String callingAttributionTag) {
Daulet Zhanguzinee674252020-03-26 12:30:39 +00007217 Objects.requireNonNull(operation, "PendingIntent cannot be null.");
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007218 final int callingUid = mDeps.getCallingUid();
Paul Jensenc8873fc2015-06-17 14:15:39 -04007219 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
7220 enforceAccessPermission();
7221 }
Chalard Jeandd421992021-12-16 23:16:02 +09007222 ensureListenableCapabilities(networkCapabilities);
Chalard Jean3ec2c0f2018-04-11 21:09:10 +09007223 ensureSufficientPermissionsForRequest(networkCapabilities,
Roshan Pius08c94fb2020-01-16 12:17:17 -08007224 Binder.getCallingPid(), callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007225 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -08007226 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Chalard Jeanfd3a4ae2018-01-10 21:19:32 +09007227
7228 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittieafe8572016-07-01 13:19:21 +09007229 NetworkRequest.Type.LISTEN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007230 NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, networkRequest, operation,
7231 callingAttributionTag);
Lorenzo Colittiebf757d2016-04-08 23:09:09 +09007232 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensenc8873fc2015-06-17 14:15:39 -04007233
WeiZhang1cc3f172021-06-03 19:02:04 -05007234 mHandler.sendMessage(mHandler.obtainMessage(
7235 EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT, nri));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007236 }
7237
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007238 /** Returns the next Network provider ID. */
7239 public final int nextNetworkProviderId() {
7240 return mNextNetworkProviderId.getAndIncrement();
7241 }
7242
Erik Kline0c04b742016-07-07 16:50:58 +09007243 @Override
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007244 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti70964d32016-07-05 01:22:13 +09007245 ensureNetworkRequestHasType(networkRequest);
Erik Kline0c04b742016-07-07 16:50:58 +09007246 mHandler.sendMessage(mHandler.obtainMessage(
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +09007247 EVENT_RELEASE_NETWORK_REQUEST, mDeps.getCallingUid(), 0, networkRequest));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007248 }
7249
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007250 private void handleRegisterNetworkProvider(NetworkProviderInfo npi) {
7251 if (mNetworkProviderInfos.containsKey(npi.messenger)) {
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007252 // Avoid creating duplicates. even if an app makes a direct AIDL call.
7253 // This will never happen if an app calls ConnectivityManager#registerNetworkProvider,
7254 // as that will throw if a duplicate provider is registered.
Aaron Huang6616df32020-10-30 22:04:25 +08007255 loge("Attempt to register existing NetworkProviderInfo "
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007256 + mNetworkProviderInfos.get(npi.messenger).name);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007257 return;
7258 }
7259
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007260 if (DBG) log("Got NetworkProvider Messenger for " + npi.name);
7261 mNetworkProviderInfos.put(npi.messenger, npi);
7262 npi.connect(mContext, mTrackerHandler);
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007263 }
7264
7265 @Override
7266 public int registerNetworkProvider(Messenger messenger, String name) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007267 enforceNetworkFactoryOrSettingsPermission();
Aaron Huangc65e7fa2021-04-09 12:06:42 +08007268 Objects.requireNonNull(messenger, "messenger must be non-null");
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007269 NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
lifraf3a3492021-03-10 13:58:14 +08007270 nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007271 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
7272 return npi.providerId;
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007273 }
7274
7275 @Override
7276 public void unregisterNetworkProvider(Messenger messenger) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007277 enforceNetworkFactoryOrSettingsPermission();
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007278 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_PROVIDER, messenger));
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007279 }
7280
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007281 @Override
Chalard Jean30689b82021-03-22 22:44:02 +09007282 public void offerNetwork(final int providerId,
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007283 @NonNull final NetworkScore score, @NonNull final NetworkCapabilities caps,
7284 @NonNull final INetworkOfferCallback callback) {
Chalard Jean0354d8c2021-01-12 10:58:56 +09007285 Objects.requireNonNull(score);
7286 Objects.requireNonNull(caps);
7287 Objects.requireNonNull(callback);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007288 final boolean yieldToBadWiFi = caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007289 final NetworkOffer offer = new NetworkOffer(
Chalard Jeanbb902a52021-08-18 01:35:19 +09007290 FullScore.makeProspectiveScore(score, caps, yieldToBadWiFi),
7291 caps, callback, providerId);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007292 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_OFFER, offer));
7293 }
7294
Chalard Jeanbb902a52021-08-18 01:35:19 +09007295 private void updateOfferScore(final NetworkOffer offer) {
7296 final boolean yieldToBadWiFi =
7297 offer.caps.hasTransport(TRANSPORT_CELLULAR) && !avoidBadWifi();
7298 final NetworkOffer newOffer = new NetworkOffer(
7299 offer.score.withYieldToBadWiFi(yieldToBadWiFi),
7300 offer.caps, offer.callback, offer.providerId);
7301 if (offer.equals(newOffer)) return;
7302 handleRegisterNetworkOffer(newOffer);
7303 }
7304
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007305 @Override
7306 public void unofferNetwork(@NonNull final INetworkOfferCallback callback) {
wangshengrjxtjcb3f6c0b92022-07-22 14:59:44 +08007307 Objects.requireNonNull(callback);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007308 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_OFFER, callback));
7309 }
7310
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007311 private void handleUnregisterNetworkProvider(Messenger messenger) {
7312 NetworkProviderInfo npi = mNetworkProviderInfos.remove(messenger);
7313 if (npi == null) {
7314 loge("Failed to find Messenger in unregisterNetworkProvider");
Robert Greenwalt46dcbab2014-05-16 15:49:14 -07007315 return;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007316 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007317 // Unregister all the offers from this provider
7318 final ArrayList<NetworkOfferInfo> toRemove = new ArrayList<>();
7319 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean30689b82021-03-22 22:44:02 +09007320 if (noi.offer.providerId == npi.providerId) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007321 // Can't call handleUnregisterNetworkOffer here because iteration is in progress
7322 toRemove.add(noi);
7323 }
7324 }
Chalard Jean0354d8c2021-01-12 10:58:56 +09007325 for (final NetworkOfferInfo noi : toRemove) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007326 handleUnregisterNetworkOffer(noi);
7327 }
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007328 if (DBG) log("unregisterNetworkProvider for " + npi.name);
Robert Greenwalt7e45d112014-04-11 15:53:27 -07007329 }
7330
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007331 @Override
James Mattisf7027322020-12-13 16:28:14 -08007332 public void declareNetworkRequestUnfulfillable(@NonNull final NetworkRequest request) {
Aaron Huangebbfd3c2020-04-14 13:43:49 +08007333 if (request.hasTransport(TRANSPORT_TEST)) {
7334 enforceNetworkFactoryOrTestNetworksPermission();
7335 } else {
7336 enforceNetworkFactoryPermission();
7337 }
James Mattisf7027322020-12-13 16:28:14 -08007338 final NetworkRequestInfo nri = mNetworkRequests.get(request);
7339 if (nri != null) {
7340 // declareNetworkRequestUnfulfillable() paths don't apply to multilayer requests.
7341 ensureNotMultilayerRequest(nri, "declareNetworkRequestUnfulfillable");
7342 mHandler.post(() -> handleReleaseNetworkRequest(
7343 nri.mRequests.get(0), mDeps.getCallingUid(), true));
7344 }
Lorenzo Colitti6702d4b2020-01-08 00:04:09 +09007345 }
7346
Paul Jensen1f567382015-02-13 14:18:39 -05007347 // NOTE: Accessed on multiple threads, must be synchronized on itself.
7348 @GuardedBy("mNetworkForNetId")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007349 private final SparseArray<NetworkAgentInfo> mNetworkForNetId = new SparseArray<>();
Paul Jensen1f567382015-02-13 14:18:39 -05007350 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007351 // An entry is first reserved with NetIdManager, prior to being added to mNetworkForNetId, so
Paul Jensen1f567382015-02-13 14:18:39 -05007352 // there may not be a strict 1:1 correlation between the two.
Remi NGUYEN VAN0d0eb152019-06-13 16:12:02 +09007353 private final NetIdManager mNetIdManager;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07007354
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09007355 // Tracks all NetworkAgents that are currently registered.
Paul Jensen1f567382015-02-13 14:18:39 -05007356 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007357 private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007358
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09007359 // UID ranges for users that are currently blocked by VPNs.
7360 // This array is accessed and iterated on multiple threads without holding locks, so its
7361 // contents must never be mutated. When the ranges change, the array is replaced with a new one
7362 // (on the handler thread).
7363 private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
7364
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007365 // Must only be accessed on the handler thread
7366 @NonNull
7367 private final ArrayList<NetworkOfferInfo> mNetworkOffers = new ArrayList<>();
7368
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007369 @GuardedBy("mBlockedAppUids")
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007370 private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
Lorenzo Colittiac136a02016-01-22 04:04:57 +09007371
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007372 // Current OEM network preferences. This object must only be written to on the handler thread.
7373 // Since it is immutable and always non-null, other threads may read it if they only care
7374 // about seeing a consistent object but not that it is current.
James Mattis45d81842021-01-10 14:24:24 -08007375 @NonNull
7376 private OemNetworkPreferences mOemNetworkPreferences =
7377 new OemNetworkPreferences.Builder().build();
Chalard Jeanb5a139f2021-02-25 21:46:34 +09007378 // Current per-profile network preferences. This object follows the same threading rules as
7379 // the OEM network preferences above.
7380 @NonNull
Chalard Jean0606fc82022-12-14 20:34:43 +09007381 private NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo>
7382 mProfileNetworkPreferences = new NetworkPreferenceList<>();
James Mattis45d81842021-01-10 14:24:24 -08007383
lucaslin3ba7cc22022-12-19 02:35:33 +00007384 // Current VPN network preferences. This object follows the same threading rules as the OEM
7385 // network preferences above.
7386 @NonNull
7387 private NetworkPreferenceList<String, VpnNetworkPreferenceInfo>
7388 mVpnNetworkPreferences = new NetworkPreferenceList<>();
7389
paulhu51f77dc2021-06-07 02:34:20 +00007390 // A set of UIDs that should use mobile data preferentially if available. This object follows
7391 // the same threading rules as the OEM network preferences above.
7392 @NonNull
7393 private Set<Integer> mMobileDataPreferredUids = new ArraySet<>();
7394
James Mattiscb1e0362021-04-06 17:07:42 -07007395 // OemNetworkPreferences activity String log entries.
7396 private static final int MAX_OEM_NETWORK_PREFERENCE_LOGS = 20;
7397 @NonNull
7398 private final LocalLog mOemNetworkPreferencesLogs =
7399 new LocalLog(MAX_OEM_NETWORK_PREFERENCE_LOGS);
7400
James Mattis02220e22021-03-13 19:27:21 -08007401 /**
7402 * Determine whether a given package has a mapping in the current OemNetworkPreferences.
7403 * @param packageName the package name to check existence of a mapping for.
7404 * @return true if a mapping exists, false otherwise
7405 */
7406 private boolean isMappedInOemNetworkPreference(@NonNull final String packageName) {
7407 return mOemNetworkPreferences.getNetworkPreferences().containsKey(packageName);
7408 }
7409
James Mattise3ef1912020-12-20 11:09:58 -08007410 // The always-on request for an Internet-capable network that apps without a specific default
7411 // fall back to.
James Mattis45d81842021-01-10 14:24:24 -08007412 @VisibleForTesting
Chalard Jean2c8b3e32019-11-05 14:40:23 +09007413 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007414 final NetworkRequestInfo mDefaultRequest;
James Mattise3ef1912020-12-20 11:09:58 -08007415 // Collection of NetworkRequestInfo's used for default networks.
James Mattis45d81842021-01-10 14:24:24 -08007416 @VisibleForTesting
James Mattise3ef1912020-12-20 11:09:58 -08007417 @NonNull
James Mattis45d81842021-01-10 14:24:24 -08007418 final ArraySet<NetworkRequestInfo> mDefaultNetworkRequests = new ArraySet<>();
Chalard Jeand4f01ca2018-05-18 22:02:56 +09007419
James Mattisd31bdfa2020-12-23 16:37:26 -08007420 private boolean isPerAppDefaultRequest(@NonNull final NetworkRequestInfo nri) {
7421 return (mDefaultNetworkRequests.contains(nri) && mDefaultRequest != nri);
7422 }
7423
7424 /**
James Mattis3ce3d3c2021-02-09 18:18:28 -08007425 * Return the default network request currently tracking the given uid.
7426 * @param uid the uid to check.
7427 * @return the NetworkRequestInfo tracking the given uid.
7428 */
7429 @NonNull
James Mattis02220e22021-03-13 19:27:21 -08007430 private NetworkRequestInfo getDefaultRequestTrackingUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007431 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007432 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007433 // Checking the first request is sufficient as only multilayer requests will have more
7434 // than one request and for multilayer, all requests will track the same uids.
7435 if (nri.mRequests.get(0).networkCapabilities.appliesToUid(uid)) {
paulhuaa0743d2021-05-26 21:56:03 +08007436 // Find out the highest priority request.
paulhu48291862021-07-14 14:53:57 +08007437 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007438 highestPriorityNri = nri;
7439 }
James Mattis3ce3d3c2021-02-09 18:18:28 -08007440 }
7441 }
paulhuaa0743d2021-05-26 21:56:03 +08007442 return highestPriorityNri;
James Mattis3ce3d3c2021-02-09 18:18:28 -08007443 }
7444
7445 /**
7446 * Get a copy of the network requests of the default request that is currently tracking the
7447 * given uid.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007448 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7449 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007450 * @param requestorUid the uid to check the default for.
7451 * @param requestorPackageName the requestor's package name.
7452 * @return a copy of the default's NetworkRequest that is tracking the given uid.
7453 */
7454 @NonNull
7455 private List<NetworkRequest> copyDefaultNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007456 final int asUid, final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007457 return copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007458 getDefaultRequestTrackingUid(asUid).mRequests,
7459 asUid, requestorUid, requestorPackageName);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007460 }
7461
7462 /**
7463 * Copy the given nri's NetworkRequest collection.
7464 * @param requestsToCopy the NetworkRequest collection to be copied.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007465 * @param asUid the uid on behalf of which to file the request. Different from requestorUid
7466 * when a privileged caller is tracking the default network for another uid.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007467 * @param requestorUid the uid to set on the copied collection.
7468 * @param requestorPackageName the package name to set on the copied collection.
7469 * @return the copied NetworkRequest collection.
7470 */
7471 @NonNull
7472 private List<NetworkRequest> copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007473 @NonNull final List<NetworkRequest> requestsToCopy, final int asUid,
7474 final int requestorUid, @NonNull final String requestorPackageName) {
James Mattis3ce3d3c2021-02-09 18:18:28 -08007475 final List<NetworkRequest> requests = new ArrayList<>();
7476 for (final NetworkRequest nr : requestsToCopy) {
7477 requests.add(new NetworkRequest(copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007478 nr.networkCapabilities, asUid, requestorUid, requestorPackageName),
James Mattis3ce3d3c2021-02-09 18:18:28 -08007479 nr.legacyType, nextNetworkRequestId(), nr.type));
7480 }
7481 return requests;
7482 }
7483
7484 @NonNull
7485 private NetworkCapabilities copyDefaultNetworkCapabilitiesForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007486 @NonNull final NetworkCapabilities netCapToCopy, final int asUid,
7487 final int requestorUid, @NonNull final String requestorPackageName) {
Lorenzo Colitti84593442021-03-22 02:12:04 +09007488 // These capabilities are for a TRACK_DEFAULT callback, so:
7489 // 1. Remove NET_CAPABILITY_VPN, because it's (currently!) the only difference between
7490 // mDefaultRequest and a per-UID default request.
7491 // TODO: stop depending on the fact that these two unrelated things happen to be the same
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007492 // 2. Always set the UIDs to asUid. restrictRequestUidsForCallerAndSetRequestorInfo will
Lorenzo Colitti84593442021-03-22 02:12:04 +09007493 // not do this in the case of a privileged application.
James Mattis3ce3d3c2021-02-09 18:18:28 -08007494 final NetworkCapabilities netCap = new NetworkCapabilities(netCapToCopy);
7495 netCap.removeCapability(NET_CAPABILITY_NOT_VPN);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09007496 netCap.setSingleUid(asUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -08007497 restrictRequestUidsForCallerAndSetRequestorInfo(
7498 netCap, requestorUid, requestorPackageName);
7499 return netCap;
7500 }
7501
7502 /**
7503 * Get the nri that is currently being tracked for callbacks by per-app defaults.
7504 * @param nr the network request to check for equality against.
7505 * @return the nri if one exists, null otherwise.
7506 */
7507 @Nullable
7508 private NetworkRequestInfo getNriForAppRequest(@NonNull final NetworkRequest nr) {
7509 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
7510 if (nri.getNetworkRequestForCallback().equals(nr)) {
7511 return nri;
7512 }
7513 }
7514 return null;
7515 }
7516
7517 /**
7518 * Check if an nri is currently being managed by per-app default networking.
7519 * @param nri the nri to check.
7520 * @return true if this nri is currently being managed by per-app default networking.
7521 */
7522 private boolean isPerAppTrackedNri(@NonNull final NetworkRequestInfo nri) {
7523 // nri.mRequests.get(0) is only different from the original request filed in
7524 // nri.getNetworkRequestForCallback() if nri.mRequests was changed by per-app default
7525 // functionality therefore if these two don't match, it means this particular nri is
7526 // currently being managed by a per-app default.
7527 return nri.getNetworkRequestForCallback() != nri.mRequests.get(0);
7528 }
7529
7530 /**
James Mattisd31bdfa2020-12-23 16:37:26 -08007531 * Determine if an nri is a managed default request that disallows default networking.
7532 * @param nri the request to evaluate
7533 * @return true if device-default networking is disallowed
7534 */
7535 private boolean isDefaultBlocked(@NonNull final NetworkRequestInfo nri) {
7536 // Check if this nri is a managed default that supports the default network at its
7537 // lowest priority request.
7538 final NetworkRequest defaultNetworkRequest = mDefaultRequest.mRequests.get(0);
7539 final NetworkCapabilities lowestPriorityNetCap =
7540 nri.mRequests.get(nri.mRequests.size() - 1).networkCapabilities;
7541 return isPerAppDefaultRequest(nri)
7542 && !(defaultNetworkRequest.networkCapabilities.equalRequestableCapabilities(
7543 lowestPriorityNetCap));
7544 }
7545
Erik Kline05f2b402015-04-30 12:58:40 +09007546 // Request used to optionally keep mobile data active even when higher
7547 // priority networks like Wi-Fi are active.
7548 private final NetworkRequest mDefaultMobileDataRequest;
7549
Leif Hendrik Wilden838c6612018-05-02 12:05:24 -07007550 // Request used to optionally keep wifi data active even when higher
7551 // priority networks like ethernet are active.
7552 private final NetworkRequest mDefaultWifiRequest;
7553
Tomasz Wasilczyk54605b82020-12-14 13:42:51 -08007554 // Request used to optionally keep vehicle internal network always active
7555 private final NetworkRequest mDefaultVehicleRequest;
7556
James Mattisd31bdfa2020-12-23 16:37:26 -08007557 // Sentinel NAI used to direct apps with default networks that should have no connectivity to a
7558 // network with no service. This NAI should never be matched against, nor should any public API
7559 // ever return the associated network. For this reason, this NAI is not in the list of available
7560 // NAIs. It is used in computeNetworkReassignment() to be set as the satisfier for non-device
7561 // default requests that don't support using the device default network which will ultimately
7562 // allow ConnectivityService to use this no-service network when calling makeDefaultForApps().
7563 @VisibleForTesting
7564 final NetworkAgentInfo mNoServiceNetwork;
7565
Chalard Jean5b409c72021-02-04 13:12:59 +09007566 // The NetworkAgentInfo currently satisfying the default request, if any.
7567 private NetworkAgentInfo getDefaultNetwork() {
7568 return mDefaultRequest.mSatisfier;
Lorenzo Colitti79bd2e22014-11-28 11:21:30 +09007569 }
7570
James Mattis2516da32021-01-31 17:06:19 -08007571 private NetworkAgentInfo getDefaultNetworkForUid(final int uid) {
paulhuaa0743d2021-05-26 21:56:03 +08007572 NetworkRequestInfo highestPriorityNri = mDefaultRequest;
James Mattis2516da32021-01-31 17:06:19 -08007573 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
7574 // Currently, all network requests will have the same uids therefore checking the first
7575 // one is sufficient. If/when uids are tracked at the nri level, this can change.
Chiachang Wang8156c4e2021-03-19 00:45:39 +00007576 final Set<UidRange> uids = nri.mRequests.get(0).networkCapabilities.getUidRanges();
James Mattis2516da32021-01-31 17:06:19 -08007577 if (null == uids) {
7578 continue;
7579 }
7580 for (final UidRange range : uids) {
7581 if (range.contains(uid)) {
paulhu48291862021-07-14 14:53:57 +08007582 if (nri.hasHigherOrderThan(highestPriorityNri)) {
paulhuaa0743d2021-05-26 21:56:03 +08007583 highestPriorityNri = nri;
7584 }
James Mattis2516da32021-01-31 17:06:19 -08007585 }
7586 }
7587 }
paulhuaa0743d2021-05-26 21:56:03 +08007588 return highestPriorityNri.getSatisfier();
James Mattis2516da32021-01-31 17:06:19 -08007589 }
7590
Varun Ananddf569952019-02-06 10:13:38 -08007591 @Nullable
7592 private Network getNetwork(@Nullable NetworkAgentInfo nai) {
7593 return nai != null ? nai.network : null;
7594 }
7595
7596 private void ensureRunningOnConnectivityServiceThread() {
7597 if (mHandler.getLooper().getThread() != Thread.currentThread()) {
7598 throw new IllegalStateException(
7599 "Not running on ConnectivityService thread: "
7600 + Thread.currentThread().getName());
7601 }
7602 }
7603
Chalard Jean3a3f5f22019-04-10 23:07:55 +09007604 @VisibleForTesting
Chalard Jean5b409c72021-02-04 13:12:59 +09007605 protected boolean isDefaultNetwork(NetworkAgentInfo nai) {
7606 return nai == getDefaultNetwork();
Robert Greenwalta1d68e72014-08-06 21:32:18 -07007607 }
7608
Chalard Jean29d06db2018-05-02 21:14:54 +09007609 /**
7610 * Register a new agent with ConnectivityService to handle a network.
7611 *
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007612 * @param na a reference for ConnectivityService to contact the agent asynchronously.
Chalard Jean29d06db2018-05-02 21:14:54 +09007613 * @param networkInfo the initial info associated with this network. It can be updated later :
7614 * see {@link #updateNetworkInfo}.
7615 * @param linkProperties the initial link properties of this network. They can be updated
7616 * later : see {@link #updateLinkProperties}.
7617 * @param networkCapabilities the initial capabilites of this network. They can be updated
Chalard Jean2e315442019-12-12 13:56:13 +09007618 * later : see {@link #updateCapabilities}.
Chalard Jeanaa5bc622022-02-26 21:34:48 +09007619 * @param initialScore the initial score of the network. See {@link NetworkAgentInfo#getScore}.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09007620 * @param networkAgentConfig metadata about the network. This is never updated.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09007621 * @param providerId the ID of the provider owning this NetworkAgent.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007622 * @return the network created for this agent.
Chalard Jean29d06db2018-05-02 21:14:54 +09007623 */
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007624 public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
Chalard Jean29d06db2018-05-02 21:14:54 +09007625 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007626 @NonNull NetworkScore initialScore, NetworkAgentConfig networkAgentConfig,
7627 int providerId) {
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007628 Objects.requireNonNull(networkInfo, "networkInfo must not be null");
7629 Objects.requireNonNull(linkProperties, "linkProperties must not be null");
7630 Objects.requireNonNull(networkCapabilities, "networkCapabilities must not be null");
Chalard Jean28018572020-12-21 18:36:52 +09007631 Objects.requireNonNull(initialScore, "initialScore must not be null");
Lorenzo Colittibb4d45f2021-01-18 14:15:17 +09007632 Objects.requireNonNull(networkAgentConfig, "networkAgentConfig must not be null");
Chalard Jean5b639762020-03-09 21:25:37 +09007633 if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
paulhu3ffffe72021-09-16 10:15:22 +08007634 enforceAnyPermissionOf(mContext, Manifest.permission.MANAGE_TEST_NETWORKS);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007635 } else {
7636 enforceNetworkFactoryPermission();
7637 }
7638
Lorenzo Colittif61ca942020-12-15 11:02:22 +09007639 final int uid = mDeps.getCallingUid();
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007640 final long token = Binder.clearCallingIdentity();
7641 try {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007642 return registerNetworkAgentInternal(na, networkInfo, linkProperties,
Chalard Jean28018572020-12-21 18:36:52 +09007643 networkCapabilities, initialScore, networkAgentConfig, providerId, uid);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007644 } finally {
7645 Binder.restoreCallingIdentity(token);
7646 }
7647 }
7648
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007649 private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007650 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Chalard Jean28018572020-12-21 18:36:52 +09007651 NetworkScore currentScore, NetworkAgentConfig networkAgentConfig, int providerId,
7652 int uid) {
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007653
Chalard Jeandbc46952022-02-02 00:14:18 +09007654 // Make a copy of the passed NI, LP, NC as the caller may hold a reference to them
7655 // and mutate them at any time.
7656 final NetworkInfo niCopy = new NetworkInfo(networkInfo);
7657 final NetworkCapabilities ncCopy = new NetworkCapabilities(networkCapabilities);
7658 final LinkProperties lpCopy = new LinkProperties(linkProperties);
7659
Chalard Jean366c5252022-01-25 18:27:53 +09007660 // At this point the capabilities/properties are untrusted and unverified, e.g. checks that
Chalard Jeandbc46952022-02-02 00:14:18 +09007661 // the capabilities' access UIDs comply with security limitations. They will be sanitized
Chalard Jean366c5252022-01-25 18:27:53 +09007662 // as the NAI registration finishes, in handleRegisterNetworkAgent(). This is
7663 // because some of the checks must happen on the handler thread.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007664 final NetworkAgentInfo nai = new NetworkAgentInfo(na,
Chalard Jeandbc46952022-02-02 00:14:18 +09007665 new Network(mNetIdManager.reserveNetId()), niCopy, lpCopy, ncCopy,
Chalard Jean8cdee3a2020-03-04 17:45:08 +09007666 currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
Chalard Jean550b5212021-03-05 23:07:53 +09007667 this, mNetd, mDnsResolver, providerId, uid, mLingerDelayMs,
7668 mQosCallbackTracker, mDeps);
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007669
Chalard Jeandbc46952022-02-02 00:14:18 +09007670 final String extraInfo = niCopy.getExtraInfo();
Chalard Jeanf2da1772018-04-26 16:16:10 +09007671 final String name = TextUtils.isEmpty(extraInfo)
Chalard Jean542e6002020-03-18 15:58:50 +09007672 ? nai.networkCapabilities.getSsid() : extraInfo;
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007673 if (DBG) log("registerNetworkAgent " + nai);
Lorenzo Colitti8000e032020-11-26 23:42:25 +09007674 mDeps.getNetworkStack().makeNetworkMonitor(
7675 nai.network, name, new NetworkMonitorCallbacks(nai));
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007676 // NetworkAgentInfo registration will finish when the NetworkMonitor is created.
7677 // If the network disconnects or sends any other event before that, messages are deferred by
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007678 // NetworkAgent until nai.connect(), which will be called when finalizing the
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007679 // registration.
Chalard Jeanf78c9642019-12-13 19:47:12 +09007680 return nai.network;
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007681 }
7682
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007683 private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
Chalard Jean366c5252022-01-25 18:27:53 +09007684 if (VDBG) log("Network Monitor created for " + nai);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007685 // Store a copy of the declared capabilities.
Chalard Jean39b12d42022-02-27 12:08:49 +09007686 nai.setDeclaredCapabilities(nai.networkCapabilities);
Chalard Jeanda7fe572022-02-01 23:47:23 +09007687 // Make sure the LinkProperties and NetworkCapabilities reflect what the agent info said.
Chalard Jeandbc46952022-02-02 00:14:18 +09007688 nai.getAndSetNetworkCapabilities(mixInCapabilities(nai,
7689 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator)));
7690 processLinkPropertiesFromAgent(nai, nai.linkProperties);
Chalard Jean366c5252022-01-25 18:27:53 +09007691
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007692 nai.onNetworkMonitorCreated(networkMonitor);
Chalard Jean366c5252022-01-25 18:27:53 +09007693
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007694 mNetworkAgentInfos.add(nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007695 synchronized (mNetworkForNetId) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007696 mNetworkForNetId.put(nai.network.getNetId(), nai);
Paul Jensen1f567382015-02-13 14:18:39 -05007697 }
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007698
7699 try {
7700 networkMonitor.start();
7701 } catch (RemoteException e) {
Chiachang Wang8c778c92019-04-24 21:44:05 +08007702 e.rethrowAsRuntimeException();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09007703 }
Chalard Jean366c5252022-01-25 18:27:53 +09007704
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09007705 nai.notifyRegistered();
Erik Kline286974f2018-03-04 21:01:01 +09007706 NetworkInfo networkInfo = nai.networkInfo;
Erik Kline286974f2018-03-04 21:01:01 +09007707 updateNetworkInfo(nai, networkInfo);
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00007708 updateVpnUids(nai, null, nai.networkCapabilities);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007709 }
7710
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007711 private class NetworkOfferInfo implements IBinder.DeathRecipient {
7712 @NonNull public final NetworkOffer offer;
7713
7714 NetworkOfferInfo(@NonNull final NetworkOffer offer) {
7715 this.offer = offer;
7716 }
7717
7718 @Override
7719 public void binderDied() {
7720 mHandler.post(() -> handleUnregisterNetworkOffer(this));
7721 }
7722 }
7723
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007724 private boolean isNetworkProviderWithIdRegistered(final int providerId) {
7725 for (final NetworkProviderInfo npi : mNetworkProviderInfos.values()) {
7726 if (npi.providerId == providerId) return true;
7727 }
7728 return false;
7729 }
7730
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007731 /**
7732 * Register or update a network offer.
7733 * @param newOffer The new offer. If the callback member is the same as an existing
7734 * offer, it is an update of that offer.
7735 */
Chalard Jeanbb902a52021-08-18 01:35:19 +09007736 // TODO : rename this to handleRegisterOrUpdateNetworkOffer
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007737 private void handleRegisterNetworkOffer(@NonNull final NetworkOffer newOffer) {
7738 ensureRunningOnConnectivityServiceThread();
Chalard Jeandd35f2d2021-03-24 14:31:38 +09007739 if (!isNetworkProviderWithIdRegistered(newOffer.providerId)) {
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007740 // This may actually happen if a provider updates its score or registers and then
7741 // immediately unregisters. The offer would still be in the handler queue, but the
7742 // provider would have been removed.
7743 if (DBG) log("Received offer from an unregistered provider");
7744 return;
7745 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007746 final NetworkOfferInfo existingOffer = findNetworkOfferInfoByCallback(newOffer.callback);
7747 if (null != existingOffer) {
7748 handleUnregisterNetworkOffer(existingOffer);
7749 newOffer.migrateFrom(existingOffer.offer);
Chalard Jeanbb902a52021-08-18 01:35:19 +09007750 if (DBG) {
7751 // handleUnregisterNetworkOffer has already logged the old offer
7752 log("update offer from providerId " + newOffer.providerId + " new : " + newOffer);
7753 }
7754 } else {
7755 if (DBG) {
7756 log("register offer from providerId " + newOffer.providerId + " : " + newOffer);
7757 }
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007758 }
7759 final NetworkOfferInfo noi = new NetworkOfferInfo(newOffer);
7760 try {
Chalard Jean30689b82021-03-22 22:44:02 +09007761 noi.offer.callback.asBinder().linkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007762 } catch (RemoteException e) {
7763 noi.binderDied();
7764 return;
7765 }
7766 mNetworkOffers.add(noi);
Chalard Jean0354d8c2021-01-12 10:58:56 +09007767 issueNetworkNeeds(noi);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007768 }
7769
7770 private void handleUnregisterNetworkOffer(@NonNull final NetworkOfferInfo noi) {
7771 ensureRunningOnConnectivityServiceThread();
Chalard Jeanbb902a52021-08-18 01:35:19 +09007772 if (DBG) {
7773 log("unregister offer from providerId " + noi.offer.providerId + " : " + noi.offer);
7774 }
Tyler Wear3ec7e6d2021-08-17 18:25:50 -07007775
7776 // If the provider removes the offer and dies immediately afterwards this
7777 // function may be called twice in a row, but the array will no longer contain
7778 // the offer.
7779 if (!mNetworkOffers.remove(noi)) return;
Chalard Jean30689b82021-03-22 22:44:02 +09007780 noi.offer.callback.asBinder().unlinkToDeath(noi, 0 /* flags */);
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007781 }
7782
7783 @Nullable private NetworkOfferInfo findNetworkOfferInfoByCallback(
7784 @NonNull final INetworkOfferCallback callback) {
7785 ensureRunningOnConnectivityServiceThread();
7786 for (final NetworkOfferInfo noi : mNetworkOffers) {
Chalard Jean9f6d4472021-04-08 17:37:36 +09007787 if (noi.offer.callback.asBinder().equals(callback.asBinder())) return noi;
Chalard Jeancdd68bc2021-01-05 08:40:09 +09007788 }
7789 return null;
7790 }
7791
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007792 /**
7793 * Called when receiving LinkProperties directly from a NetworkAgent.
7794 * Stores into |nai| any data coming from the agent that might also be written to the network's
7795 * LinkProperties by ConnectivityService itself. This ensures that the data provided by the
7796 * agent is not lost when updateLinkProperties is called.
Lorenzo Colitti96883c92020-12-02 13:58:47 +09007797 * This method should never alter the agent's LinkProperties, only store data in |nai|.
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09007798 */
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007799 private void processLinkPropertiesFromAgent(NetworkAgentInfo nai, LinkProperties lp) {
7800 lp.ensureDirectlyConnectedRoutes();
Lorenzo Colittie2eade02020-04-01 22:25:16 +09007801 nai.clatd.setNat64PrefixFromRa(lp.getNat64Prefix());
Hai Shalome58bdc62021-01-11 18:45:34 -08007802 nai.networkAgentPortalData = lp.getCaptivePortalData();
Lorenzo Colitti18a58462020-04-16 01:52:40 +09007803 }
7804
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09007805 private void updateLinkProperties(NetworkAgentInfo networkAgent, @NonNull LinkProperties newLp,
Junyu Lai2ed7d412022-10-07 16:52:21 +08007806 @Nullable LinkProperties oldLp) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08007807 int netId = networkAgent.network.getNetId();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007808
Lorenzo Colittid523d142020-04-01 20:16:30 +09007809 // The NetworkAgent does not know whether clatd is running on its network or not, or whether
7810 // a NAT64 prefix was discovered by the DNS resolver. Before we do anything else, make sure
7811 // the LinkProperties for the network are accurate.
Lorenzo Colitti7b0732f2019-01-08 14:43:37 +09007812 networkAgent.clatd.fixupLinkProperties(oldLp, newLp);
Lorenzo Colitticef8aec2014-09-20 13:47:47 +09007813
Suprabh Shukla1e312032023-01-24 03:36:37 -08007814 updateInterfaces(newLp, oldLp, netId, networkAgent);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00007815
7816 // update filtering rules, need to happen after the interface update so netd knows about the
7817 // new interface (the interface name -> index map becomes initialized)
7818 updateVpnFiltering(newLp, oldLp, networkAgent);
7819
Robert Greenwalte20f7a22014-04-18 15:25:25 -07007820 updateMtu(newLp, oldLp);
7821 // TODO - figure out what to do for clat
7822// for (LinkProperties lp : newLp.getStackedLinks()) {
7823// updateMtu(lp, null);
7824// }
Chalard Jean5b409c72021-02-04 13:12:59 +09007825 if (isDefaultNetwork(networkAgent)) {
lucaslin821c9782018-11-28 19:27:52 +08007826 updateTcpBufferSizes(newLp.getTcpBufferSizes());
7827 }
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007828
Erik Klineb9888902016-04-05 13:30:49 +09007829 updateRoutes(newLp, oldLp, netId);
7830 updateDnses(newLp, oldLp, netId);
dalyk1720e542018-03-05 12:42:22 -05007831 // Make sure LinkProperties represents the latest private DNS status.
7832 // This does not need to be done before updateDnses because the
7833 // LinkProperties are not the source of the private DNS configuration.
7834 // updateDnses will fetch the private DNS configuration from DnsManager.
7835 mDnsManager.updatePrivateDnsStatus(netId, newLp);
Lorenzo Colitti20068c22014-11-28 20:07:46 +09007836
Chalard Jean5b409c72021-02-04 13:12:59 +09007837 if (isDefaultNetwork(networkAgent)) {
Paul Jensenc0618a62014-12-10 15:12:18 -05007838 handleApplyDefaultProxy(newLp.getHttpProxy());
7839 } else {
Chalard Jeand6c33dc2018-06-04 13:33:12 +09007840 updateProxy(newLp, oldLp);
Paul Jensenc0618a62014-12-10 15:12:18 -05007841 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02007842
7843 updateWakeOnLan(newLp);
7844
Hai Shalome58bdc62021-01-11 18:45:34 -08007845 // Captive portal data is obtained from NetworkMonitor and stored in NetworkAgentInfo.
7846 // It is not always contained in the LinkProperties sent from NetworkAgents, and if it
7847 // does, it needs to be merged here.
7848 newLp.setCaptivePortalData(mergeCaptivePortalData(networkAgent.networkAgentPortalData,
7849 networkAgent.capportApiData));
Remi NGUYEN VAN45e11182019-12-12 12:57:11 +09007850
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007851 // TODO - move this check to cover the whole function
7852 if (!Objects.equals(newLp, oldLp)) {
Chalard Jean8397a842018-05-23 09:07:51 +09007853 synchronized (networkAgent) {
7854 networkAgent.linkProperties = newLp;
7855 }
Lorenzo Colitti84298d82019-02-19 13:21:56 +09007856 // Start or stop DNS64 detection and 464xlat according to network state.
7857 networkAgent.clatd.update();
Junyu Lai2ed7d412022-10-07 16:52:21 +08007858 // Notify NSS when relevant events happened. Currently, NSS only cares about
7859 // interface changed to update clat interfaces accounting.
7860 final boolean interfacesChanged = oldLp == null
7861 || !Objects.equals(newLp.getAllInterfaceNames(), oldLp.getAllInterfaceNames());
7862 if (interfacesChanged) {
7863 notifyIfacesChangedForNetworkStats();
7864 }
Remi NGUYEN VANc9f24742020-05-10 16:11:11 +09007865 networkAgent.networkMonitor().notifyLinkPropertiesChanged(
7866 new LinkProperties(newLp, true /* parcelSensitiveFields */));
Lorenzo Colitti275ee602022-08-09 19:29:12 +09007867 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07007868 }
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09007869
7870 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3927e332014-05-13 11:44:01 -04007871 }
7872
Hai Shalome58bdc62021-01-11 18:45:34 -08007873 /**
7874 * @param naData captive portal data from NetworkAgent
7875 * @param apiData captive portal data from capport API
7876 */
7877 @Nullable
7878 private CaptivePortalData mergeCaptivePortalData(CaptivePortalData naData,
7879 CaptivePortalData apiData) {
7880 if (naData == null || apiData == null) {
7881 return naData == null ? apiData : naData;
7882 }
7883 final CaptivePortalData.Builder captivePortalBuilder =
7884 new CaptivePortalData.Builder(naData);
7885
7886 if (apiData.isCaptive()) {
7887 captivePortalBuilder.setCaptive(true);
7888 }
7889 if (apiData.isSessionExtendable()) {
7890 captivePortalBuilder.setSessionExtendable(true);
7891 }
7892 if (apiData.getExpiryTimeMillis() >= 0 || apiData.getByteLimit() >= 0) {
7893 // Expiry time, bytes remaining, refresh time all need to come from the same source,
7894 // otherwise data would be inconsistent. Prefer the capport API info if present,
7895 // as it can generally be refreshed more often.
7896 captivePortalBuilder.setExpiryTime(apiData.getExpiryTimeMillis());
7897 captivePortalBuilder.setBytesRemaining(apiData.getByteLimit());
7898 captivePortalBuilder.setRefreshTime(apiData.getRefreshTimeMillis());
7899 } else if (naData.getExpiryTimeMillis() < 0 && naData.getByteLimit() < 0) {
7900 // No source has time / bytes remaining information: surface the newest refresh time
7901 // for other fields
7902 captivePortalBuilder.setRefreshTime(
7903 Math.max(naData.getRefreshTimeMillis(), apiData.getRefreshTimeMillis()));
7904 }
7905
Hai Shalom7c6ab402021-02-04 19:34:06 -08007906 // Prioritize the user portal URL from the network agent if the source is authenticated.
7907 if (apiData.getUserPortalUrl() != null && naData.getUserPortalUrlSource()
7908 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7909 captivePortalBuilder.setUserPortalUrl(apiData.getUserPortalUrl(),
7910 apiData.getUserPortalUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007911 }
Hai Shalom7c6ab402021-02-04 19:34:06 -08007912 // Prioritize the venue information URL from the network agent if the source is
7913 // authenticated.
7914 if (apiData.getVenueInfoUrl() != null && naData.getVenueInfoUrlSource()
7915 != CaptivePortalData.CAPTIVE_PORTAL_DATA_SOURCE_PASSPOINT) {
7916 captivePortalBuilder.setVenueInfoUrl(apiData.getVenueInfoUrl(),
7917 apiData.getVenueInfoUrlSource());
Hai Shalome58bdc62021-01-11 18:45:34 -08007918 }
7919 return captivePortalBuilder.build();
7920 }
7921
Suprabh Shukla1e312032023-01-24 03:36:37 -08007922 private String makeNflogPrefix(String iface, long networkHandle) {
7923 // This needs to be kept in sync and backwards compatible with the decoding logic in
7924 // NetdEventListenerService, which is non-mainline code.
7925 return SdkLevel.isAtLeastU() ? (networkHandle + ":" + iface) : ("iface:" + iface);
7926 }
7927
Suprabh Shukla75642282023-04-25 23:15:43 -07007928 private static boolean isWakeupMarkingSupported(NetworkCapabilities capabilities) {
7929 if (capabilities.hasTransport(TRANSPORT_WIFI)) {
7930 return true;
7931 }
7932 if (SdkLevel.isAtLeastU() && capabilities.hasTransport(TRANSPORT_CELLULAR)) {
7933 return true;
7934 }
7935 return false;
7936 }
7937
Suprabh Shukla1e312032023-01-24 03:36:37 -08007938 private void wakeupModifyInterface(String iface, NetworkAgentInfo nai, boolean add) {
Chalard Jean9dd11612018-06-04 16:52:49 +09007939 // Marks are only available on WiFi interfaces. Checking for
Joel Scherpelza235a812017-05-22 13:47:41 +09007940 // marks on unsupported interfaces is harmless.
Suprabh Shukla75642282023-04-25 23:15:43 -07007941 if (!isWakeupMarkingSupported(nai.networkCapabilities)) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007942 return;
7943 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007944
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09007945 int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
7946 int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
7947
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007948 // Mask/mark of zero will not detect anything interesting.
7949 // Don't install rules unless both values are nonzero.
7950 if (mark == 0 || mask == 0) {
Joel Scherpelza235a812017-05-22 13:47:41 +09007951 return;
7952 }
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007953
Suprabh Shukla1e312032023-01-24 03:36:37 -08007954 final String prefix = makeNflogPrefix(iface, nai.network.getNetworkHandle());
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007955 try {
7956 if (add) {
Luke Huang46289a22018-09-27 19:33:11 +08007957 mNetd.wakeupAddInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007958 } else {
Luke Huang46289a22018-09-27 19:33:11 +08007959 mNetd.wakeupDelInterface(iface, prefix, mark, mask);
Joel Scherpelz946a3c92017-06-08 15:35:21 +09007960 }
7961 } catch (Exception e) {
7962 loge("Exception modifying wakeup packet monitoring: " + e);
7963 }
Joel Scherpelza235a812017-05-22 13:47:41 +09007964 }
7965
Junyu Lai970963e2022-10-25 15:46:47 +08007966 private void updateInterfaces(final @NonNull LinkProperties newLp,
Chalard Jean9589e722019-11-19 19:03:53 +09007967 final @Nullable LinkProperties oldLp, final int netId,
Suprabh Shukla1e312032023-01-24 03:36:37 -08007968 final @NonNull NetworkAgentInfo nai) {
Chalard Jean9589e722019-11-19 19:03:53 +09007969 final CompareResult<String> interfaceDiff = new CompareResult<>(
Junyu Lai970963e2022-10-25 15:46:47 +08007970 oldLp != null ? oldLp.getAllInterfaceNames() : null, newLp.getAllInterfaceNames());
Chalard Jean9589e722019-11-19 19:03:53 +09007971 if (!interfaceDiff.added.isEmpty()) {
Chalard Jean9589e722019-11-19 19:03:53 +09007972 for (final String iface : interfaceDiff.added) {
7973 try {
7974 if (DBG) log("Adding iface " + iface + " to network " + netId);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007975 mNetd.networkAddInterface(netId, iface);
Suprabh Shukla1e312032023-01-24 03:36:37 -08007976 wakeupModifyInterface(iface, nai, true);
Aaron Huang330a4c02020-10-27 03:36:19 +08007977 mDeps.reportNetworkInterfaceForTransports(mContext, iface,
Suprabh Shukla1e312032023-01-24 03:36:37 -08007978 nai.networkCapabilities.getTransportTypes());
Chalard Jean9589e722019-11-19 19:03:53 +09007979 } catch (Exception e) {
lucaslinecdaf232021-04-01 19:17:08 +08007980 logw("Exception adding interface: " + e);
Chalard Jean9589e722019-11-19 19:03:53 +09007981 }
Paul Jensenbff73492014-04-28 10:33:11 -04007982 }
7983 }
Chalard Jean9589e722019-11-19 19:03:53 +09007984 for (final String iface : interfaceDiff.removed) {
Paul Jensenbff73492014-04-28 10:33:11 -04007985 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07007986 if (DBG) log("Removing iface " + iface + " from network " + netId);
Suprabh Shukla1e312032023-01-24 03:36:37 -08007987 wakeupModifyInterface(iface, nai, false);
Chiachang Wangf83a7182020-10-26 14:23:52 +08007988 mNetd.networkRemoveInterface(netId, iface);
Paul Jensenbff73492014-04-28 10:33:11 -04007989 } catch (Exception e) {
7990 loge("Exception removing interface: " + e);
7991 }
7992 }
7993 }
7994
Tyler Weare4314862019-12-05 14:55:30 -08007995 // TODO: move to frameworks/libs/net.
7996 private RouteInfoParcel convertRouteInfo(RouteInfo route) {
7997 final String nextHop;
7998
7999 switch (route.getType()) {
8000 case RouteInfo.RTN_UNICAST:
8001 if (route.hasGateway()) {
8002 nextHop = route.getGateway().getHostAddress();
8003 } else {
8004 nextHop = INetd.NEXTHOP_NONE;
8005 }
8006 break;
8007 case RouteInfo.RTN_UNREACHABLE:
8008 nextHop = INetd.NEXTHOP_UNREACHABLE;
8009 break;
8010 case RouteInfo.RTN_THROW:
8011 nextHop = INetd.NEXTHOP_THROW;
8012 break;
8013 default:
8014 nextHop = INetd.NEXTHOP_NONE;
8015 break;
8016 }
8017
8018 final RouteInfoParcel rip = new RouteInfoParcel();
8019 rip.ifName = route.getInterface();
8020 rip.destination = route.getDestination().toString();
8021 rip.nextHop = nextHop;
8022 rip.mtu = route.getMtu();
8023
8024 return rip;
8025 }
8026
Paul Jensene0fd4a82014-08-06 15:51:33 -04008027 /**
8028 * Have netd update routes from oldLp to newLp.
8029 * @return true if routes changed between oldLp and newLp
8030 */
Junyu Lai970963e2022-10-25 15:46:47 +08008031 private boolean updateRoutes(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8032 int netId) {
Tyler Weare4314862019-12-05 14:55:30 -08008033 // compare the route diff to determine which routes have been updated
junyulaia1493a52020-03-23 20:49:43 +08008034 final CompareOrUpdateResult<RouteInfo.RouteKey, RouteInfo> routeDiff =
8035 new CompareOrUpdateResult<>(
8036 oldLp != null ? oldLp.getAllRoutes() : null,
Junyu Lai970963e2022-10-25 15:46:47 +08008037 newLp.getAllRoutes(),
junyulaia1493a52020-03-23 20:49:43 +08008038 (r) -> r.getRouteKey());
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008039
8040 // add routes before removing old in case it helps with continuous connectivity
8041
Chalard Jean9dd11612018-06-04 16:52:49 +09008042 // do this twice, adding non-next-hop routes first, then routes they are dependent on
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008043 for (RouteInfo route : routeDiff.added) {
8044 if (route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008045 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008046 try {
Tyler Weare4314862019-12-05 14:55:30 -08008047 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008048 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008049 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008050 loge("Exception in networkAddRouteParcel for non-gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008051 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008052 }
8053 }
8054 for (RouteInfo route : routeDiff.added) {
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008055 if (!route.hasGateway()) continue;
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008056 if (VDBG || DDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008057 try {
Tyler Weare4314862019-12-05 14:55:30 -08008058 mNetd.networkAddRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008059 } catch (Exception e) {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008060 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
Tyler Weare4314862019-12-05 14:55:30 -08008061 loge("Exception in networkAddRouteParcel for gateway: " + e);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008062 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008063 }
8064 }
8065
8066 for (RouteInfo route : routeDiff.removed) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008067 if (VDBG || DDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008068 try {
Tyler Weare4314862019-12-05 14:55:30 -08008069 mNetd.networkRemoveRouteParcel(netId, convertRouteInfo(route));
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008070 } catch (Exception e) {
Tyler Weare4314862019-12-05 14:55:30 -08008071 loge("Exception in networkRemoveRouteParcel: " + e);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008072 }
8073 }
Tyler Weare4314862019-12-05 14:55:30 -08008074
8075 for (RouteInfo route : routeDiff.updated) {
8076 if (VDBG || DDBG) log("Updating Route [" + route + "] from network " + netId);
8077 try {
8078 mNetd.networkUpdateRouteParcel(netId, convertRouteInfo(route));
8079 } catch (Exception e) {
8080 loge("Exception in networkUpdateRouteParcel: " + e);
8081 }
8082 }
8083 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty()
8084 || !routeDiff.updated.isEmpty();
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008085 }
Erik Kline0f0dbb82015-06-17 13:19:54 +09008086
Junyu Lai970963e2022-10-25 15:46:47 +08008087 private void updateDnses(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8088 int netId) {
Erik Klineb9888902016-04-05 13:30:49 +09008089 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
8090 return; // no updating necessary
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008091 }
Erik Klineb9888902016-04-05 13:30:49 +09008092
Erik Kline31b4a9e2018-01-11 21:07:29 +09008093 if (DBG) {
8094 final Collection<InetAddress> dnses = newLp.getDnsServers();
8095 log("Setting DNS servers for network " + netId + " to " + dnses);
8096 }
Erik Klineb9888902016-04-05 13:30:49 +09008097 try {
chenbruce7b2f8982020-02-20 14:28:31 +08008098 mDnsManager.noteDnsServersForNetwork(netId, newLp);
chenbruce7b2f8982020-02-20 14:28:31 +08008099 mDnsManager.flushVmDnsCache();
Erik Klineb9888902016-04-05 13:30:49 +09008100 } catch (Exception e) {
Pierre Imai21664692016-04-28 17:00:04 +09008101 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Klineb9888902016-04-05 13:30:49 +09008102 }
Erik Kline54e35c02017-04-07 15:29:29 +09008103 }
8104
Junyu Lai970963e2022-10-25 15:46:47 +08008105 private void updateVpnFiltering(@NonNull LinkProperties newLp, @Nullable LinkProperties oldLp,
8106 @NonNull NetworkAgentInfo nai) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008107 final String oldIface = getVpnIsolationInterface(nai, nai.networkCapabilities, oldLp);
8108 final String newIface = getVpnIsolationInterface(nai, nai.networkCapabilities, newLp);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008109 final boolean wasFiltering = requiresVpnAllowRule(nai, oldLp, oldIface);
8110 final boolean needsFiltering = requiresVpnAllowRule(nai, newLp, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008111
8112 if (!wasFiltering && !needsFiltering) {
8113 // Nothing to do.
8114 return;
8115 }
8116
8117 if (Objects.equals(oldIface, newIface) && (wasFiltering == needsFiltering)) {
8118 // Nothing changed.
8119 return;
8120 }
8121
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008122 final Set<UidRange> ranges = nai.networkCapabilities.getUidRanges();
Motomu Utsumib08654c2022-05-11 05:56:26 +00008123 if (ranges == null || ranges.isEmpty()) {
8124 return;
8125 }
8126
Qingxi Libb8da982020-01-17 17:54:27 -08008127 final int vpnAppUid = nai.networkCapabilities.getOwnerUid();
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008128 // TODO: this create a window of opportunity for apps to receive traffic between the time
8129 // when the old rules are removed and the time when new rules are added. To fix this,
Jeff Sharkey39f8e972020-09-11 15:10:20 -06008130 // make eBPF support two allowlisted interfaces so here new rules can be added before the
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008131 // old rules are being removed.
8132 if (wasFiltering) {
8133 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, ranges, vpnAppUid);
8134 }
8135 if (needsFiltering) {
8136 mPermissionMonitor.onVpnUidRangesAdded(newIface, ranges, vpnAppUid);
8137 }
8138 }
8139
Valentin Iftime9fa35092019-09-24 13:32:13 +02008140 private void updateWakeOnLan(@NonNull LinkProperties lp) {
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008141 if (mWolSupportedInterfaces == null) {
8142 mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09008143 R.array.config_wakeonlan_supported_interfaces));
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09008144 }
Valentin Iftime9fa35092019-09-24 13:32:13 +02008145 lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
8146 }
8147
Luke Huangb913c812018-08-24 20:33:16 +08008148 private int getNetworkPermission(NetworkCapabilities nc) {
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008149 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Luke Huangb913c812018-08-24 20:33:16 +08008150 return INetd.PERMISSION_SYSTEM;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008151 }
8152 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Luke Huangb913c812018-08-24 20:33:16 +08008153 return INetd.PERMISSION_NETWORK;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008154 }
Luke Huangb913c812018-08-24 20:33:16 +08008155 return INetd.PERMISSION_NONE;
Lorenzo Colittib8d9f522016-07-28 17:14:11 +09008156 }
8157
Chalard Jean62edfd82019-12-02 18:39:29 +09008158 private void updateNetworkPermissions(@NonNull final NetworkAgentInfo nai,
8159 @NonNull final NetworkCapabilities newNc) {
8160 final int oldPermission = getNetworkPermission(nai.networkCapabilities);
8161 final int newPermission = getNetworkPermission(newNc);
Chalard Jean254bd162022-08-25 13:04:51 +09008162 if (oldPermission != newPermission && nai.isCreated() && !nai.isVPN()) {
Chalard Jean62edfd82019-12-02 18:39:29 +09008163 try {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008164 mNetd.networkSetPermissionForNetwork(nai.network.getNetId(), newPermission);
Chiachang Wangedb833a2020-10-26 19:59:31 +08008165 } catch (RemoteException | ServiceSpecificException e) {
8166 loge("Exception in networkSetPermissionForNetwork: " + e);
Chalard Jean62edfd82019-12-02 18:39:29 +09008167 }
8168 }
8169 }
8170
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008171 /** Modifies |newNc| based on the capabilities of |underlyingNetworks| and |agentCaps|. */
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008172 @VisibleForTesting
Lorenzo Colittid7caf832020-12-01 01:08:37 +09008173 void applyUnderlyingCapabilities(@Nullable Network[] underlyingNetworks,
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008174 @NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
James Mattis2516da32021-01-31 17:06:19 -08008175 underlyingNetworks = underlyingNetworksOrDefault(
8176 agentCaps.getOwnerUid(), underlyingNetworks);
Chalard Jean1d420b32022-10-12 16:39:37 +09008177 long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008178 int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
8179 int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008180 // metered if any underlying is metered, or originally declared metered by the agent.
8181 boolean metered = !agentCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008182 boolean roaming = false; // roaming if any underlying is roaming
8183 boolean congested = false; // congested if any underlying is congested
8184 boolean suspended = true; // suspended if all underlying are suspended
8185
8186 boolean hadUnderlyingNetworks = false;
lucaslin6adf5ac2021-10-19 15:04:56 +08008187 ArrayList<Network> newUnderlyingNetworks = null;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008188 if (null != underlyingNetworks) {
lucaslin6adf5ac2021-10-19 15:04:56 +08008189 newUnderlyingNetworks = new ArrayList<>();
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008190 for (Network underlyingNetwork : underlyingNetworks) {
8191 final NetworkAgentInfo underlying =
8192 getNetworkAgentInfoForNetwork(underlyingNetwork);
8193 if (underlying == null) continue;
8194
8195 final NetworkCapabilities underlyingCaps = underlying.networkCapabilities;
8196 hadUnderlyingNetworks = true;
8197 for (int underlyingType : underlyingCaps.getTransportTypes()) {
Remi NGUYEN VAN3d159fc2020-12-01 17:47:12 +09008198 transportTypes |= 1L << underlyingType;
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008199 }
8200
8201 // Merge capabilities of this underlying network. For bandwidth, assume the
8202 // worst case.
8203 downKbps = NetworkCapabilities.minBandwidth(downKbps,
8204 underlyingCaps.getLinkDownstreamBandwidthKbps());
8205 upKbps = NetworkCapabilities.minBandwidth(upKbps,
8206 underlyingCaps.getLinkUpstreamBandwidthKbps());
8207 // If this underlying network is metered, the VPN is metered (it may cost money
8208 // to send packets on this network).
8209 metered |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_METERED);
8210 // If this underlying network is roaming, the VPN is roaming (the billing structure
8211 // is different than the usual, local one).
8212 roaming |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8213 // If this underlying network is congested, the VPN is congested (the current
8214 // condition of the network affects the performance of this network).
8215 congested |= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_CONGESTED);
8216 // If this network is not suspended, the VPN is not suspended (the VPN
8217 // is able to transfer some data).
8218 suspended &= !underlyingCaps.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
lucaslin6adf5ac2021-10-19 15:04:56 +08008219 newUnderlyingNetworks.add(underlyingNetwork);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008220 }
8221 }
8222 if (!hadUnderlyingNetworks) {
8223 // No idea what the underlying networks are; assume reasonable defaults
8224 metered = true;
8225 roaming = false;
8226 congested = false;
8227 suspended = false;
8228 }
8229
Chalard Jean1d420b32022-10-12 16:39:37 +09008230 newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008231 newNc.setLinkDownstreamBandwidthKbps(downKbps);
8232 newNc.setLinkUpstreamBandwidthKbps(upKbps);
8233 newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
8234 newNc.setCapability(NET_CAPABILITY_NOT_ROAMING, !roaming);
8235 newNc.setCapability(NET_CAPABILITY_NOT_CONGESTED, !congested);
8236 newNc.setCapability(NET_CAPABILITY_NOT_SUSPENDED, !suspended);
lucaslin6adf5ac2021-10-19 15:04:56 +08008237 newNc.setUnderlyingNetworks(newUnderlyingNetworks);
Lorenzo Colitticda101b2020-11-24 21:45:25 +09008238 }
8239
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008240 /**
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008241 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
8242 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
8243 * and foreground status).
Paul Jensen53f08952015-06-16 14:27:36 -04008244 */
Remi NGUYEN VANdf5f3112021-01-28 15:09:22 +09008245 @NonNull
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008246 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi9712eb32017-08-16 13:19:04 +09008247 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008248 // Don't complain for VPNs since they're not driven by requests and there is no risk of
8249 // causing a connect/teardown loop.
Lorenzo Colittia86fae72020-01-10 00:40:28 +09008250 // TODO: remove this altogether and make it the responsibility of the NetworkProviders to
Lorenzo Colitti614891d2018-05-30 16:44:47 +09008251 // avoid connect/teardown loops.
Chalard Jean254bd162022-08-25 13:04:51 +09008252 if (nai.everConnected()
8253 && !nai.isVPN()
8254 && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008255 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi9712eb32017-08-16 13:19:04 +09008256 // does not cause any request (that is not a listen) currently matching that agent to
8257 // stop being matched by the updated agent.
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008258 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichid9806e82017-07-25 11:40:56 +09008259 if (!TextUtils.isEmpty(diff)) {
Aaron Huang6616df32020-10-30 22:04:25 +08008260 Log.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichid9806e82017-07-25 11:40:56 +09008261 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008262 }
8263
Paul Jensen53f08952015-06-16 14:27:36 -04008264 // Don't modify caller's NetworkCapabilities.
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008265 final NetworkCapabilities newNc = new NetworkCapabilities(nc);
Chalard Jean254bd162022-08-25 13:04:51 +09008266 if (nai.isValidated()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008267 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008268 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008269 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen53f08952015-06-16 14:27:36 -04008270 }
Chalard Jean254bd162022-08-25 13:04:51 +09008271 if (nai.captivePortalDetected()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008272 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008273 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008274 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen53f08952015-06-16 14:27:36 -04008275 }
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008276 if (nai.isBackgroundNetwork()) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008277 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008278 } else {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008279 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008280 }
Chalard Jean254bd162022-08-25 13:04:51 +09008281 if (nai.partialConnectivity()) {
lucaslin2240ef62019-03-12 13:08:03 +08008282 newNc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8283 } else {
8284 newNc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
8285 }
lucasline117e2e2019-10-22 18:27:33 +08008286 newNc.setPrivateDnsBroken(nai.networkCapabilities.isPrivateDnsBroken());
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008287
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008288 // TODO : remove this once all factories are updated to send NOT_SUSPENDED and NOT_ROAMING
Chalard Jeand61375d2020-01-14 22:46:36 +09008289 if (!newNc.hasTransport(TRANSPORT_CELLULAR)) {
8290 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09008291 newNc.addCapability(NET_CAPABILITY_NOT_ROAMING);
Chalard Jeand61375d2020-01-14 22:46:36 +09008292 }
8293
Lorenzo Colittibd079452021-07-02 11:47:57 +09008294 if (nai.propagateUnderlyingCapabilities()) {
Chalard Jeanda7fe572022-02-01 23:47:23 +09008295 applyUnderlyingCapabilities(nai.declaredUnderlyingNetworks,
Chalard Jean39b12d42022-02-27 12:08:49 +09008296 nai.getDeclaredCapabilitiesSanitized(mCarrierPrivilegeAuthenticator),
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008297 newNc);
Lorenzo Colitti129c01e2020-11-09 10:32:56 +09008298 }
8299
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008300 return newNc;
8301 }
8302
Lorenzo Colitti44840702021-01-11 22:27:57 +09008303 private void updateNetworkInfoForRoamingAndSuspended(NetworkAgentInfo nai,
8304 NetworkCapabilities prevNc, NetworkCapabilities newNc) {
8305 final boolean prevSuspended = !prevNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8306 final boolean suspended = !newNc.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
8307 final boolean prevRoaming = !prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8308 final boolean roaming = !newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
8309 if (prevSuspended != suspended) {
8310 // TODO (b/73132094) : remove this call once the few users of onSuspended and
8311 // onResumed have been removed.
8312 notifyNetworkCallbacks(nai, suspended ? ConnectivityManager.CALLBACK_SUSPENDED
8313 : ConnectivityManager.CALLBACK_RESUMED);
8314 }
8315 if (prevSuspended != suspended || prevRoaming != roaming) {
8316 // updateNetworkInfo will mix in the suspended info from the capabilities and
8317 // take appropriate action for the network having possibly changed state.
8318 updateNetworkInfo(nai, nai.networkInfo);
8319 }
8320 }
8321
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008322 /**
8323 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
8324 *
8325 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
8326 * capabilities we manage and store in {@code nai}, such as validated status and captive
8327 * portal status)
8328 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
8329 * potentially triggers rematches.
8330 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
8331 * change.)
8332 *
8333 * @param oldScore score of the network before any of the changes that prompted us
8334 * to call this function.
8335 * @param nai the network having its capabilities updated.
8336 * @param nc the new network capabilities.
8337 */
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008338 private void updateCapabilities(final FullScore oldScore, @NonNull final NetworkAgentInfo nai,
Chalard Jean62edfd82019-12-02 18:39:29 +09008339 @NonNull final NetworkCapabilities nc) {
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008340 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
Lorenzo Colitti46f96cb2018-01-16 00:52:07 +09008341 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Chalard Jean86317d82022-10-12 16:18:04 +09008342 final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
8343 if (null != differences) {
8344 Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
8345 }
Chalard Jean62edfd82019-12-02 18:39:29 +09008346 updateNetworkPermissions(nai, newNc);
Chalard Jean05edd052019-11-22 22:39:56 +09008347 final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008348
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008349 updateVpnUids(nai, prevNc, newNc);
Chalard Jeande665262022-02-25 16:12:12 +09008350 updateAllowedUids(nai, prevNc, newNc);
Chalard Jean142f0fe2021-03-31 23:19:05 +09008351 nai.updateScoreForNetworkAgentUpdate();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008352
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008353 if (nai.getScore().equals(oldScore) && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008354 // If the requestable capabilities haven't changed, and the score hasn't changed, then
8355 // the change we're processing can't affect any requests, it can only affect the listens
8356 // on this network. We might have been called by rematchNetworkAndRequests when a
8357 // network changed foreground state.
Chalard Jean05cbe972019-12-09 11:50:38 +09008358 processListenRequests(nai);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008359 } else {
8360 // If the requestable capabilities have changed or the score changed, we can't have been
8361 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09008362 rematchAllNetworksAndRequests();
Paul Jensende49eb12015-06-25 15:30:08 -04008363 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07008364 }
Lorenzo Colitti44840702021-01-11 22:27:57 +09008365 updateNetworkInfoForRoamingAndSuspended(nai, prevNc, newNc);
Jeff Sharkey07e19362017-10-27 17:22:59 -06008366
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008367 final boolean oldMetered = prevNc.isMetered();
8368 final boolean newMetered = newNc.isMetered();
8369 final boolean meteredChanged = oldMetered != newMetered;
junyulaif2c67e42018-08-07 19:50:45 +08008370
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008371 if (meteredChanged) {
Sudheer Shanka9967d462021-03-18 19:09:25 +00008372 maybeNotifyNetworkBlocked(nai, oldMetered, newMetered,
8373 mVpnBlockedUidRanges, mVpnBlockedUidRanges);
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008374 }
junyulaif2c67e42018-08-07 19:50:45 +08008375
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008376 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING)
8377 != newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
junyulaif2c67e42018-08-07 19:50:45 +08008378
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008379 // Report changes that are interesting for network statistics tracking.
Aaron Huangc5a05d12022-12-01 21:11:12 +08008380 if (meteredChanged || roamingChanged) {
Lorenzo Colitti59fa1272021-01-16 00:23:46 +09008381 notifyIfacesChangedForNetworkStats();
Jeff Sharkey07e19362017-10-27 17:22:59 -06008382 }
8383
Lorenzo Colitti96dba632020-12-02 00:48:09 +09008384 // This network might have been underlying another network. Propagate its capabilities.
8385 propagateUnderlyingNetworkCapabilities(nai.network);
chenbruce7b2f8982020-02-20 14:28:31 +08008386
8387 if (!newNc.equalsTransportTypes(prevNc)) {
Serik Beketayevec8ad212020-12-07 22:43:07 -08008388 mDnsManager.updateTransportsForNetwork(
8389 nai.network.getNetId(), newNc.getTransportTypes());
chenbruce7b2f8982020-02-20 14:28:31 +08008390 }
lucaslin53e8a262021-06-08 01:43:59 +08008391
8392 maybeSendProxyBroadcast(nai, prevNc, newNc);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008393 }
8394
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008395 /** Convenience method to update the capabilities for a given network. */
8396 private void updateCapabilitiesForNetwork(NetworkAgentInfo nai) {
Chalard Jeanaa5bc622022-02-26 21:34:48 +09008397 updateCapabilities(nai.getScore(), nai, nai.networkCapabilities);
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008398 }
8399
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008400 /**
Motomu Utsumi77a79482022-05-16 04:04:34 +00008401 * Returns the interface which requires VPN isolation (ingress interface filtering).
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008402 *
8403 * Ingress interface filtering enforces that all apps under the given network can only receive
8404 * packets from the network's interface (and loopback). This is important for VPNs because
8405 * apps that cannot bypass a fully-routed VPN shouldn't be able to receive packets from any
8406 * non-VPN interfaces.
8407 *
Motomu Utsumi77a79482022-05-16 04:04:34 +00008408 * As a result, this method should return Non-null interface iff
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008409 * 1. the network is an app VPN (not legacy VPN)
8410 * 2. the VPN does not allow bypass
8411 * 3. the VPN is fully-routed
8412 * 4. the VPN interface is non-null
8413 *
Chalard Jeanfbab6d42019-09-26 18:03:47 +09008414 * @see INetd#firewallAddUidInterfaceRules
8415 * @see INetd#firewallRemoveUidInterfaceRules
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008416 */
Motomu Utsumi77a79482022-05-16 04:04:34 +00008417 @Nullable
8418 private String getVpnIsolationInterface(@NonNull NetworkAgentInfo nai, NetworkCapabilities nc,
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008419 LinkProperties lp) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008420 if (nc == null || lp == null) return null;
8421 if (nai.isVPN()
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09008422 && !nai.networkAgentConfig.allowBypass
Qingxi Libb8da982020-01-17 17:54:27 -08008423 && nc.getOwnerUid() != Process.SYSTEM_UID
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008424 && lp.getInterfaceName() != null
lucaslinec9ab792020-11-02 16:05:02 +08008425 && (lp.hasIpv4DefaultRoute() || lp.hasIpv4UnreachableDefaultRoute())
Prerana2b97bbe2022-04-28 04:02:05 +00008426 && (lp.hasIpv6DefaultRoute() || lp.hasIpv6UnreachableDefaultRoute())
Motomu Utsumi77a79482022-05-16 04:04:34 +00008427 && !lp.hasExcludeRoute()) {
8428 return lp.getInterfaceName();
8429 }
8430 return null;
8431 }
8432
8433 /**
8434 * Returns whether we need to set interface filtering rule or not
8435 */
Motomu Utsumib08654c2022-05-11 05:56:26 +00008436 private boolean requiresVpnAllowRule(NetworkAgentInfo nai, LinkProperties lp,
Motomu Utsumif8bd82c2022-05-30 12:28:04 +00008437 String isolationIface) {
8438 // Allow rules are always needed if VPN isolation is enabled.
8439 if (isolationIface != null) return true;
8440
8441 // On T and above, allow rules are needed for all VPNs. Allow rule with null iface is a
8442 // wildcard to allow apps to receive packets on all interfaces. This is required to accept
8443 // incoming traffic in Lockdown mode by overriding the Lockdown blocking rule.
8444 return SdkLevel.isAtLeastT() && nai.isVPN() && lp != null && lp.getInterfaceName() != null;
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008445 }
8446
Chiachang Wang28afaff2020-12-10 22:24:47 +08008447 private static UidRangeParcel[] toUidRangeStableParcels(final @NonNull Set<UidRange> ranges) {
8448 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.size()];
8449 int index = 0;
8450 for (UidRange range : ranges) {
8451 stableRanges[index] = new UidRangeParcel(range.start, range.stop);
8452 index++;
8453 }
8454 return stableRanges;
8455 }
8456
Chalard Jeane6c95272022-01-25 21:04:21 +09008457 private static UidRangeParcel[] intsToUidRangeStableParcels(
8458 final @NonNull ArraySet<Integer> uids) {
8459 final UidRangeParcel[] stableRanges = new UidRangeParcel[uids.size()];
8460 int index = 0;
8461 for (int uid : uids) {
8462 stableRanges[index] = new UidRangeParcel(uid, uid);
8463 index++;
8464 }
8465 return stableRanges;
8466 }
8467
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008468 private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
8469 final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
8470 for (int i = 0; i < ranges.length; i++) {
8471 stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
8472 }
8473 return stableRanges;
8474 }
8475
Motomu Utsumi93a22182023-03-16 17:04:21 +09008476 private void maybeCloseSockets(NetworkAgentInfo nai, Set<UidRange> ranges,
8477 Set<Integer> exemptUids) {
Ken Chen5e65a852020-12-24 12:59:10 +08008478 if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
8479 try {
Motomu Utsumi93a22182023-03-16 17:04:21 +09008480 mDeps.destroyLiveTcpSockets(UidRange.toIntRanges(ranges), exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008481 } catch (Exception e) {
8482 loge("Exception in socket destroy: ", e);
8483 }
8484 }
8485 }
8486
paulhuaa0743d2021-05-26 21:56:03 +08008487 private void updateVpnUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
Motomu Utsumi93a22182023-03-16 17:04:21 +09008488 final Set<Integer> exemptUids = new ArraySet<>();
Ken Chen5e65a852020-12-24 12:59:10 +08008489 // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
8490 // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
8491 // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
Motomu Utsumi93a22182023-03-16 17:04:21 +09008492 exemptUids.add(VPN_UID);
8493 exemptUids.add(nai.networkCapabilities.getOwnerUid());
Ken Chen5e65a852020-12-24 12:59:10 +08008494 UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
8495
Motomu Utsumi6345e462023-03-13 13:24:50 +09008496 // Close sockets before modifying uid ranges so that RST packets can reach to the server.
Motomu Utsumi93a22182023-03-16 17:04:21 +09008497 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008498 try {
8499 if (add) {
paulhu0e79d952021-06-09 16:11:35 +08008500 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008501 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008502 } else {
paulhu0e79d952021-06-09 16:11:35 +08008503 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
paulhu48291862021-07-14 14:53:57 +08008504 nai.network.netId, ranges, PREFERENCE_ORDER_VPN));
Ken Chen5e65a852020-12-24 12:59:10 +08008505 }
8506 } catch (Exception e) {
8507 loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
8508 " on netId " + nai.network.netId + ". " + e);
8509 }
Motomu Utsumi6345e462023-03-13 13:24:50 +09008510 // Close sockets that established connection while requesting netd.
Motomu Utsumi93a22182023-03-16 17:04:21 +09008511 maybeCloseSockets(nai, uidRanges, exemptUids);
Ken Chen5e65a852020-12-24 12:59:10 +08008512 }
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09008513
lucaslin53e8a262021-06-08 01:43:59 +08008514 private boolean isProxySetOnAnyDefaultNetwork() {
8515 ensureRunningOnConnectivityServiceThread();
8516 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
8517 final NetworkAgentInfo nai = nri.getSatisfier();
8518 if (nai != null && nai.linkProperties.getHttpProxy() != null) {
8519 return true;
8520 }
8521 }
8522 return false;
8523 }
8524
8525 private void maybeSendProxyBroadcast(NetworkAgentInfo nai, NetworkCapabilities prevNc,
8526 NetworkCapabilities newNc) {
8527 // When the apps moved from/to a VPN, a proxy broadcast is needed to inform the apps that
8528 // the proxy might be changed since the default network satisfied by the apps might also
8529 // changed.
8530 // TODO: Try to track the default network that apps use and only send a proxy broadcast when
8531 // that happens to prevent false alarms.
Chalard Jeanf4802fa2021-12-13 21:37:12 +09008532 final Set<UidRange> prevUids = prevNc == null ? null : prevNc.getUidRanges();
8533 final Set<UidRange> newUids = newNc == null ? null : newNc.getUidRanges();
Chalard Jean254bd162022-08-25 13:04:51 +09008534 if (nai.isVPN() && nai.everConnected() && !UidRange.hasSameUids(prevUids, newUids)
lucaslin53e8a262021-06-08 01:43:59 +08008535 && (nai.linkProperties.getHttpProxy() != null || isProxySetOnAnyDefaultNetwork())) {
8536 mProxyTracker.sendProxyBroadcast();
8537 }
8538 }
8539
Chalard Jeane6c95272022-01-25 21:04:21 +09008540 private void updateVpnUids(@NonNull NetworkAgentInfo nai, @Nullable NetworkCapabilities prevNc,
8541 @Nullable NetworkCapabilities newNc) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +00008542 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUidRanges();
8543 Set<UidRange> newRanges = null == newNc ? null : newNc.getUidRanges();
Chalard Jeanb2a49912018-01-16 18:43:05 +09008544 if (null == prevRanges) prevRanges = new ArraySet<>();
8545 if (null == newRanges) newRanges = new ArraySet<>();
8546 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
8547
8548 prevRanges.removeAll(newRanges);
8549 newRanges.removeAll(prevRangesCopy);
8550
8551 try {
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008552 // When updating the VPN uid routing rules, add the new range first then remove the old
8553 // range. If old range were removed first, there would be a window between the old
8554 // range being removed and the new range being added, during which UIDs contained
8555 // in both ranges are not subject to any VPN routing rules. Adding new range before
8556 // removing old range works because, unlike the filtering rules below, it's possible to
8557 // add duplicate UID routing rules.
Ken Chen5e65a852020-12-24 12:59:10 +08008558 // TODO: calculate the intersection of add & remove. Imagining that we are trying to
8559 // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
8560 // [1-5] & [1-2],[4-5] == [3]
8561 // Then we can do:
8562 // maybeCloseSockets([3])
8563 // mNetd.networkAddUidRanges([1-2],[4-5])
8564 // mNetd.networkRemoveUidRanges([1-5])
8565 // maybeCloseSockets([3])
8566 // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
8567 // number of binder calls from 6 to 4.
Chalard Jeanb2a49912018-01-16 18:43:05 +09008568 if (!newRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008569 updateVpnUidRanges(true, nai, newRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008570 }
8571 if (!prevRanges.isEmpty()) {
paulhuaa0743d2021-05-26 21:56:03 +08008572 updateVpnUidRanges(false, nai, prevRanges);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008573 }
Motomu Utsumi77a79482022-05-16 04:04:34 +00008574 final String oldIface = getVpnIsolationInterface(nai, prevNc, nai.linkProperties);
8575 final String newIface = getVpnIsolationInterface(nai, newNc, nai.linkProperties);
Motomu Utsumib08654c2022-05-11 05:56:26 +00008576 final boolean wasFiltering = requiresVpnAllowRule(nai, nai.linkProperties, oldIface);
8577 final boolean shouldFilter = requiresVpnAllowRule(nai, nai.linkProperties, newIface);
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008578 // For VPN uid interface filtering, old ranges need to be removed before new ranges can
Chalard Jeana5ff1132020-05-20 16:11:50 +09008579 // be added, due to the range being expanded and stored as individual UIDs. For example
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008580 // the UIDs might be updated from [0, 99999] to ([0, 10012], [10014, 99999]) which means
8581 // prevRanges = [0, 99999] while newRanges = [0, 10012], [10014, 99999]. If prevRanges
8582 // were added first and then newRanges got removed later, there would be only one uid
8583 // 10013 left. A consequence of removing old ranges before adding new ranges is that
8584 // there is now a window of opportunity when the UIDs are not subject to any filtering.
8585 // Note that this is in contrast with the (more robust) update of VPN routing rules
8586 // above, where the addition of new ranges happens before the removal of old ranges.
8587 // TODO Fix this window by computing an accurate diff on Set<UidRange>, so the old range
8588 // to be removed will never overlap with the new range to be added.
8589 if (wasFiltering && !prevRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008590 mPermissionMonitor.onVpnUidRangesRemoved(oldIface, prevRanges,
8591 prevNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008592 }
8593 if (shouldFilter && !newRanges.isEmpty()) {
Motomu Utsumi77a79482022-05-16 04:04:34 +00008594 mPermissionMonitor.onVpnUidRangesAdded(newIface, newRanges, newNc.getOwnerUid());
Lorenzo Colittibad9d912019-04-12 10:48:06 +00008595 }
Chalard Jeanb2a49912018-01-16 18:43:05 +09008596 } catch (Exception e) {
8597 // Never crash!
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008598 loge("Exception in updateVpnUids: ", e);
Chalard Jeanb2a49912018-01-16 18:43:05 +09008599 }
8600 }
8601
Chalard Jeande665262022-02-25 16:12:12 +09008602 private void updateAllowedUids(@NonNull NetworkAgentInfo nai,
Chalard Jeane6c95272022-01-25 21:04:21 +09008603 @Nullable NetworkCapabilities prevNc, @Nullable NetworkCapabilities newNc) {
8604 // In almost all cases both NC code for empty access UIDs. return as fast as possible.
Chalard Jeande665262022-02-25 16:12:12 +09008605 final boolean prevEmpty = null == prevNc || prevNc.getAllowedUidsNoCopy().isEmpty();
8606 final boolean newEmpty = null == newNc || newNc.getAllowedUidsNoCopy().isEmpty();
Chalard Jeane6c95272022-01-25 21:04:21 +09008607 if (prevEmpty && newEmpty) return;
8608
8609 final ArraySet<Integer> prevUids =
Chalard Jeande665262022-02-25 16:12:12 +09008610 null == prevNc ? new ArraySet<>() : prevNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008611 final ArraySet<Integer> newUids =
Chalard Jeande665262022-02-25 16:12:12 +09008612 null == newNc ? new ArraySet<>() : newNc.getAllowedUidsNoCopy();
Chalard Jeane6c95272022-01-25 21:04:21 +09008613
8614 if (prevUids.equals(newUids)) return;
8615
8616 // This implementation is very simple and vastly faster for sets of Integers than
8617 // CompareOrUpdateResult, which is tuned for sets that need to be compared based on
8618 // a key computed from the value and has storage for that.
8619 final ArraySet<Integer> toRemove = new ArraySet<>(prevUids);
8620 final ArraySet<Integer> toAdd = new ArraySet<>(newUids);
8621 toRemove.removeAll(newUids);
8622 toAdd.removeAll(prevUids);
8623
8624 try {
8625 if (!toAdd.isEmpty()) {
8626 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
8627 nai.network.netId,
8628 intsToUidRangeStableParcels(toAdd),
8629 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8630 }
8631 if (!toRemove.isEmpty()) {
8632 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
8633 nai.network.netId,
8634 intsToUidRangeStableParcels(toRemove),
8635 PREFERENCE_ORDER_IRRELEVANT_BECAUSE_NOT_DEFAULT));
8636 }
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00008637 } catch (ServiceSpecificException e) {
8638 // Has the interface disappeared since the network was built ?
8639 Log.i(TAG, "Can't set access UIDs for network " + nai.network, e);
Chalard Jeane6c95272022-01-25 21:04:21 +09008640 } catch (RemoteException e) {
8641 // Netd died. This usually causes a runtime restart anyway.
8642 }
8643 }
8644
Junyu Lai2ed7d412022-10-07 16:52:21 +08008645 public void handleUpdateLinkProperties(@NonNull NetworkAgentInfo nai,
8646 @NonNull LinkProperties newLp) {
Lorenzo Colittibb6bacc2019-02-20 21:34:01 +09008647 ensureRunningOnConnectivityServiceThread();
8648
Lorenzo Colittib4bf0152021-06-07 15:32:04 +09008649 if (!mNetworkAgentInfos.contains(nai)) {
Hugo Benichi9d35b752017-09-01 01:23:32 +00008650 // Ignore updates for disconnected networks
8651 return;
8652 }
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09008653 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09008654 log("Update of LinkProperties for " + nai.toShortString()
Chalard Jean254bd162022-08-25 13:04:51 +09008655 + "; created=" + nai.getCreatedTime()
8656 + "; firstConnected=" + nai.getConnectedTime());
Hugo Benichi9d35b752017-09-01 01:23:32 +00008657 }
Lorenzo Colitti18a58462020-04-16 01:52:40 +09008658 // TODO: eliminate this defensive copy after confirming that updateLinkProperties does not
8659 // modify its oldLp parameter.
lucaslin74fa3972018-11-28 12:51:55 +08008660 updateLinkProperties(nai, newLp, new LinkProperties(nai.linkProperties));
Hugo Benichi9d35b752017-09-01 01:23:32 +00008661 }
8662
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008663 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
8664 int notificationType) {
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008665 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008666 Intent intent = new Intent();
Jeremy Joslinde802a22014-11-26 14:24:15 -08008667 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
James Mattisa076c532020-12-02 14:12:41 -08008668 // If apps could file multi-layer requests with PendingIntents, they'd need to know
8669 // which of the layer is satisfied alongside with some ID for the request. Hence, if
8670 // such an API is ever implemented, there is no doubt the right request to send in
Remi NGUYEN VAN1e238a82021-06-25 16:38:05 +09008671 // EXTRA_NETWORK_REQUEST is the active request, and whatever ID would be added would
8672 // need to be sent as a separate extra.
8673 final NetworkRequest req = nri.isMultilayerRequest()
8674 ? nri.getActiveRequest()
8675 // Non-multilayer listen requests do not have an active request
8676 : nri.mRequests.get(0);
8677 if (req == null) {
8678 Log.wtf(TAG, "No request in NRI " + nri);
8679 }
8680 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, req);
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008681 nri.mPendingIntentSent = true;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008682 sendIntent(nri.mPendingIntent, intent);
8683 }
8684 // else not handled
8685 }
8686
Michael Groover73f69482023-01-27 11:01:25 -06008687 // TODO(b/193460475): Remove when tooling supports SystemApi to public API.
8688 @SuppressLint("NewApi")
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008689 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
8690 mPendingIntentWakeLock.acquire();
8691 try {
8692 if (DBG) log("Sending " + pendingIntent);
chiachangwanga36518c2022-05-26 05:19:41 +00008693 final BroadcastOptions options = BroadcastOptions.makeBasic();
8694 if (SdkLevel.isAtLeastT()) {
8695 // Explicitly disallow the receiver from starting activities, to prevent apps from
8696 // utilizing the PendingIntent as a backdoor to do this.
8697 options.setPendingIntentBackgroundActivityLaunchAllowed(false);
8698 }
8699 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */,
8700 null /* requiredPermission */,
8701 SdkLevel.isAtLeastT() ? options.toBundle() : null);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008702 } catch (PendingIntent.CanceledException e) {
8703 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
8704 mPendingIntentWakeLock.release();
8705 releasePendingNetworkRequest(pendingIntent);
8706 }
8707 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
8708 }
8709
8710 @Override
8711 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
8712 String resultData, Bundle resultExtras) {
8713 if (DBG) log("Finished sending " + pendingIntent);
8714 mPendingIntentWakeLock.release();
Jeremy Joslin1d3acf92014-12-03 17:15:28 -08008715 // Release with a delay so the receiving client has an opportunity to put in its
8716 // own request.
8717 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08008718 }
8719
Chalard Jean46bfbf02022-02-02 00:56:25 +09008720 // networkAgent is only allowed to be null if notificationType is
8721 // CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
8722 // available, while all other cases are about some particular network.
James Mattis212df9e2020-12-03 19:57:41 -08008723 private void callCallbackForRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jean46bfbf02022-02-02 00:56:25 +09008724 @Nullable final NetworkAgentInfo networkAgent, final int notificationType,
James Mattis212df9e2020-12-03 19:57:41 -08008725 final int arg1) {
James Mattis45d81842021-01-10 14:24:24 -08008726 if (nri.mMessenger == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -08008727 // Default request has no msgr. Also prevents callbacks from being invoked for
8728 // NetworkRequestInfos registered with ConnectivityDiagnostics requests. Those callbacks
8729 // are Type.LISTEN, but should not have NetworkCallbacks invoked.
8730 return;
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008731 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008732 Bundle bundle = new Bundle();
James Mattis212df9e2020-12-03 19:57:41 -08008733 // TODO b/177608132: make sure callbacks are indexed by NRIs and not NetworkRequest objects.
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008734 // TODO: check if defensive copies of data is needed.
James Mattis3ce3d3c2021-02-09 18:18:28 -08008735 final NetworkRequest nrForCallback = nri.getNetworkRequestForCallback();
James Mattis212df9e2020-12-03 19:57:41 -08008736 putParcelable(bundle, nrForCallback);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008737 Message msg = Message.obtain();
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008738 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
8739 putParcelable(bundle, networkAgent.network);
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008740 }
Roshan Pius951c0032020-12-22 15:10:42 -08008741 final boolean includeLocationSensitiveInfo =
8742 (nri.mCallbackFlags & NetworkCallback.FLAG_INCLUDE_LOCATION_INFO) != 0;
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008743 switch (notificationType) {
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008744 case ConnectivityManager.CALLBACK_AVAILABLE: {
Qingxi Lib2748102020-01-08 12:51:49 -08008745 final NetworkCapabilities nc =
Roshan Pius9ed14622020-12-28 09:01:49 -08008746 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Chalard Jean713e38c2022-02-28 10:58:17 +09008747 networkCapabilitiesRestrictedForCallerPermissions(
8748 networkAgent.networkCapabilities, nri.mPid, nri.mUid),
8749 includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008750 nrForCallback.getRequestorPackageName(),
Chalard Jean713e38c2022-02-28 10:58:17 +09008751 nri.mCallingAttributionTag);
8752 putParcelable(bundle, nc);
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008753 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8754 networkAgent.linkProperties, nri.mPid, nri.mUid));
junyulaif2c67e42018-08-07 19:50:45 +08008755 // For this notification, arg1 contains the blocked status.
8756 msg.arg1 = arg1;
Chalard Jeana23bc9e2018-01-30 22:41:41 +09008757 break;
8758 }
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008759 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008760 msg.arg1 = arg1;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008761 break;
8762 }
8763 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jean2550e062018-01-26 19:24:40 +09008764 // networkAgent can't be null as it has been accessed a few lines above.
Qingxi Lib2748102020-01-08 12:51:49 -08008765 final NetworkCapabilities netCap =
8766 networkCapabilitiesRestrictedForCallerPermissions(
8767 networkAgent.networkCapabilities, nri.mPid, nri.mUid);
8768 putParcelable(
8769 bundle,
Roshan Pius9ed14622020-12-28 09:01:49 -08008770 createWithLocationInfoSanitizedIfNecessaryWhenParceled(
Roshan Pius98f59ec2021-02-23 08:47:39 -08008771 netCap, includeLocationSensitiveInfo, nri.mPid, nri.mUid,
Roshan Pius951c0032020-12-22 15:10:42 -08008772 nrForCallback.getRequestorPackageName(),
Roshan Piusaa24fde2020-12-17 14:53:09 -08008773 nri.mCallingAttributionTag));
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008774 break;
8775 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008776 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Remi NGUYEN VAN0a65eed2019-12-17 16:45:42 +09008777 putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
8778 networkAgent.linkProperties, nri.mPid, nri.mUid));
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008779 break;
8780 }
junyulaif2c67e42018-08-07 19:50:45 +08008781 case ConnectivityManager.CALLBACK_BLK_CHANGED: {
Lorenzo Colitti42fe2232021-03-25 23:17:36 +09008782 maybeLogBlockedStatusChanged(nri, networkAgent.network, arg1);
junyulaif2c67e42018-08-07 19:50:45 +08008783 msg.arg1 = arg1;
8784 break;
8785 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008786 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008787 msg.what = notificationType;
Robert Greenwalte525a0a2014-09-30 16:50:07 -07008788 msg.setData(bundle);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008789 try {
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008790 if (VDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09008791 String notification = ConnectivityManager.getCallbackName(notificationType);
James Mattis212df9e2020-12-03 19:57:41 -08008792 log("sending notification " + notification + " for " + nrForCallback);
Robert Greenwalt419e1b42014-08-27 14:34:02 -07008793 }
James Mattis45d81842021-01-10 14:24:24 -08008794 nri.mMessenger.send(msg);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008795 } catch (RemoteException e) {
8796 // may occur naturally in the race of binder death.
James Mattis212df9e2020-12-03 19:57:41 -08008797 loge("RemoteException caught trying to send a callback msg for " + nrForCallback);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07008798 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008799 }
8800
Hugo Benichif8a0f9f2017-03-23 22:40:44 +09008801 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
8802 bundle.putParcelable(t.getClass().getSimpleName(), t);
8803 }
8804
Chalard Jean0702f982021-09-16 21:50:07 +09008805 /**
8806 * Returns whether reassigning a request from an NAI to another can be done gracefully.
8807 *
8808 * When a request should be assigned to a new network, it is normally lingered to give
8809 * time for apps to gracefully migrate their connections. When both networks are on the same
8810 * radio, but that radio can't do time-sharing efficiently, this may end up being
8811 * counter-productive because any traffic on the old network may drastically reduce the
8812 * performance of the new network.
8813 * The stack supports a configuration to let modem vendors state that their radio can't
8814 * do time-sharing efficiently. If this configuration is set, the stack assumes moving
8815 * from one cell network to another can't be done gracefully.
8816 *
8817 * @param oldNai the old network serving the request
8818 * @param newNai the new network serving the request
8819 * @return whether the switch can be graceful
8820 */
8821 private boolean canSupportGracefulNetworkSwitch(@NonNull final NetworkAgentInfo oldSatisfier,
8822 @NonNull final NetworkAgentInfo newSatisfier) {
8823 if (mCellularRadioTimesharingCapable) return true;
8824 return !oldSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8825 || !newSatisfier.networkCapabilities.hasSingleTransport(TRANSPORT_CELLULAR)
8826 || !newSatisfier.getScore().hasPolicy(POLICY_TRANSPORT_PRIMARY);
8827 }
8828
Paul Jensenaf94b982014-09-30 15:37:41 -04008829 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008830 if (nai.numRequestNetworkRequests() != 0) {
8831 for (int i = 0; i < nai.numNetworkRequests(); i++) {
8832 NetworkRequest nr = nai.requestAt(i);
Lorenzo Colitti96742d92021-01-29 20:18:03 +09008833 // Ignore listening and track default requests.
8834 if (!nr.isRequest()) continue;
Lorenzo Colitti99236d12016-07-01 01:37:11 +09008835 loge("Dead network still had at least " + nr);
8836 break;
8837 }
Paul Jensenaf94b982014-09-30 15:37:41 -04008838 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09008839 nai.disconnect();
Paul Jensenaf94b982014-09-30 15:37:41 -04008840 }
8841
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008842 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
8843 if (oldNetwork == null) {
8844 loge("Unknown NetworkAgentInfo in handleLingerComplete");
8845 return;
8846 }
Chalard Jean49707572019-12-10 21:07:02 +09008847 if (DBG) log("handleLingerComplete for " + oldNetwork.toShortString());
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008848
8849 // If we get here it means that the last linger timeout for this network expired. So there
8850 // must be no other active linger timers, and we must stop lingering.
junyulai2b6f0c22021-02-03 20:15:30 +08008851 oldNetwork.clearInactivityState();
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008852
Lorenzo Colitti2666be82016-09-09 18:48:56 +09008853 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008854 // Tear the network down.
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008855 teardownUnneededNetwork(oldNetwork);
Lorenzo Colitti0f042202016-07-18 18:40:42 +09008856 } else {
junyulai0ac374f2020-12-14 18:41:52 +08008857 // Put the network in the background if it doesn't satisfy any foreground request.
Lorenzo Colittie4d1e522020-12-10 00:32:04 +09008858 updateCapabilitiesForNetwork(oldNetwork);
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09008859 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07008860 }
8861
James Mattise3ef1912020-12-20 11:09:58 -08008862 private void processDefaultNetworkChanges(@NonNull final NetworkReassignment changes) {
8863 boolean isDefaultChanged = false;
8864 for (final NetworkRequestInfo defaultRequestInfo : mDefaultNetworkRequests) {
8865 final NetworkReassignment.RequestReassignment reassignment =
8866 changes.getReassignment(defaultRequestInfo);
8867 if (null == reassignment) {
8868 continue;
8869 }
8870 // reassignment only contains those instances where the satisfying network changed.
8871 isDefaultChanged = true;
8872 // Notify system services of the new default.
8873 makeDefault(defaultRequestInfo, reassignment.mOldNetwork, reassignment.mNewNetwork);
8874 }
Chiachang Wang087fd272018-09-28 22:42:48 +08008875
James Mattise3ef1912020-12-20 11:09:58 -08008876 if (isDefaultChanged) {
8877 // Hold a wakelock for a short time to help apps in migrating to a new default.
8878 scheduleReleaseNetworkTransitionWakelock();
8879 }
8880 }
8881
8882 private void makeDefault(@NonNull final NetworkRequestInfo nri,
8883 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8884 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8885 if (DBG) {
8886 log("Switching to new default network for: " + nri + " using " + newDefaultNetwork);
8887 }
Chalard Jean8e382112019-12-03 20:45:30 +09008888
James Mattisd31bdfa2020-12-23 16:37:26 -08008889 // Fix up the NetworkCapabilities of any networks that have this network as underlying.
8890 if (newDefaultNetwork != null) {
8891 propagateUnderlyingNetworkCapabilities(newDefaultNetwork.network);
Paul Jensend0464ed2014-07-14 12:03:33 -04008892 }
Lorenzo Colitti24861882018-01-19 00:50:48 +09008893
James Mattisd31bdfa2020-12-23 16:37:26 -08008894 // Set an app level managed default and return since further processing only applies to the
8895 // default network.
8896 if (mDefaultRequest != nri) {
8897 makeDefaultForApps(nri, oldDefaultNetwork, newDefaultNetwork);
8898 return;
8899 }
8900
8901 makeDefaultNetwork(newDefaultNetwork);
8902
James Mattise3ef1912020-12-20 11:09:58 -08008903 if (oldDefaultNetwork != null) {
8904 mLingerMonitor.noteLingerDefaultNetwork(oldDefaultNetwork, newDefaultNetwork);
8905 }
8906 mNetworkActivityTracker.updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
James Mattise3ef1912020-12-20 11:09:58 -08008907 handleApplyDefaultProxy(null != newDefaultNetwork
8908 ? newDefaultNetwork.linkProperties.getHttpProxy() : null);
8909 updateTcpBufferSizes(null != newDefaultNetwork
8910 ? newDefaultNetwork.linkProperties.getTcpBufferSizes() : null);
Lorenzo Colitti24861882018-01-19 00:50:48 +09008911 notifyIfacesChangedForNetworkStats();
Paul Jensend0464ed2014-07-14 12:03:33 -04008912 }
8913
James Mattisd31bdfa2020-12-23 16:37:26 -08008914 private void makeDefaultForApps(@NonNull final NetworkRequestInfo nri,
8915 @Nullable final NetworkAgentInfo oldDefaultNetwork,
8916 @Nullable final NetworkAgentInfo newDefaultNetwork) {
8917 try {
8918 if (VDBG) {
8919 log("Setting default network for " + nri
8920 + " using UIDs " + nri.getUids()
8921 + " with old network " + (oldDefaultNetwork != null
8922 ? oldDefaultNetwork.network().getNetId() : "null")
8923 + " and new network " + (newDefaultNetwork != null
8924 ? newDefaultNetwork.network().getNetId() : "null"));
8925 }
8926 if (nri.getUids().isEmpty()) {
8927 throw new IllegalStateException("makeDefaultForApps called without specifying"
8928 + " any applications to set as the default." + nri);
8929 }
8930 if (null != newDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008931 mNetd.networkAddUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008932 newDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008933 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008934 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008935 }
8936 if (null != oldDefaultNetwork) {
paulhu0e79d952021-06-09 16:11:35 +08008937 mNetd.networkRemoveUidRangesParcel(new NativeUidRangeConfig(
James Mattisd31bdfa2020-12-23 16:37:26 -08008938 oldDefaultNetwork.network.getNetId(),
paulhu0e79d952021-06-09 16:11:35 +08008939 toUidRangeStableParcels(nri.getUids()),
paulhu48291862021-07-14 14:53:57 +08008940 nri.getPreferenceOrderForNetd()));
James Mattisd31bdfa2020-12-23 16:37:26 -08008941 }
8942 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean17215832021-03-01 14:06:28 +09008943 loge("Exception setting app default network", e);
James Mattisd31bdfa2020-12-23 16:37:26 -08008944 }
8945 }
8946
Junyu Lai35665cc2022-12-19 17:37:48 +08008947 /**
8948 * Collect restricted uid ranges for the given network and UserHandle, these uids
8949 * are not restricted for matched enterprise networks but being restricted for non-matched
8950 * enterprise networks and non-enterprise networks.
8951 */
8952 @NonNull
8953 private ArraySet<UidRange> getRestrictedUidRangesForEnterpriseBlocking(
8954 @NonNull NetworkAgentInfo nai, @NonNull UserHandle user) {
8955 final ArraySet<UidRange> restrictedUidRanges = new ArraySet<>();
8956 for (final ProfileNetworkPreferenceInfo pref : mProfileNetworkPreferences) {
8957 if (!pref.user.equals(user) || !pref.blockingNonEnterprise) continue;
8958
8959 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
8960 // The NC is built from a `ProfileNetworkPreference` which has only one
8961 // enterprise ID, so it's guaranteed to have exactly one.
8962 final int prefId = pref.capabilities.getEnterpriseIds()[0];
8963 if (nai.networkCapabilities.hasEnterpriseId(prefId)) {
8964 continue;
8965 }
8966 }
8967
8968 if (UidRangeUtils.doesRangeSetOverlap(restrictedUidRanges,
8969 pref.capabilities.getUidRanges())) {
8970 throw new IllegalArgumentException(
8971 "Overlapping uid range in preference: " + pref);
8972 }
8973 restrictedUidRanges.addAll(pref.capabilities.getUidRanges());
8974 }
8975 return restrictedUidRanges;
8976 }
8977
8978 private void updateProfileAllowedNetworks() {
Junyu Laic53a1692023-02-20 15:36:54 +08008979 // Netd command is not implemented before U.
8980 if (!SdkLevel.isAtLeastU()) return;
8981
Junyu Lai35665cc2022-12-19 17:37:48 +08008982 ensureRunningOnConnectivityServiceThread();
8983 final ArrayList<NativeUidRangeConfig> configs = new ArrayList<>();
8984 final List<UserHandle> users = mContext.getSystemService(UserManager.class)
8985 .getUserHandles(true /* excludeDying */);
8986 if (users.isEmpty()) {
8987 throw new IllegalStateException("No user is available");
8988 }
8989
8990 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
8991 ArraySet<UidRange> allowedUidRanges = new ArraySet<>();
8992 for (final UserHandle user : users) {
8993 final ArraySet<UidRange> restrictedUidRanges =
8994 getRestrictedUidRangesForEnterpriseBlocking(nai, user);
8995 allowedUidRanges.addAll(UidRangeUtils.removeRangeSetFromUidRange(
8996 UidRange.createForUser(user), restrictedUidRanges));
8997 }
8998
8999 final UidRangeParcel[] rangesParcel = toUidRangeStableParcels(allowedUidRanges);
9000 configs.add(new NativeUidRangeConfig(
9001 nai.network.netId, rangesParcel, 0 /* subPriority */));
9002 }
9003
9004 // The netd API replaces the previous configs with the current configs.
9005 // Thus, for network disconnection or preference removal, no need to
9006 // unset previous config. Instead, collecting all currently needed
9007 // configs and issue to netd.
9008 try {
9009 mNetd.setNetworkAllowlist(configs.toArray(new NativeUidRangeConfig[0]));
9010 } catch (ServiceSpecificException e) {
9011 // Has the interface disappeared since the network was built?
Junyu Laic53a1692023-02-20 15:36:54 +08009012 Log.wtf(TAG, "Unexpected ServiceSpecificException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009013 } catch (RemoteException e) {
Junyu Laic53a1692023-02-20 15:36:54 +08009014 // Netd died. This will cause a runtime restart anyway.
9015 Log.wtf(TAG, "Unexpected RemoteException", e);
Junyu Lai35665cc2022-12-19 17:37:48 +08009016 }
9017 }
9018
James Mattisd31bdfa2020-12-23 16:37:26 -08009019 private void makeDefaultNetwork(@Nullable final NetworkAgentInfo newDefaultNetwork) {
9020 try {
9021 if (null != newDefaultNetwork) {
9022 mNetd.networkSetDefault(newDefaultNetwork.network.getNetId());
9023 } else {
9024 mNetd.networkClearDefault();
9025 }
9026 } catch (RemoteException | ServiceSpecificException e) {
9027 loge("Exception setting default network :" + e);
9028 }
9029 }
9030
Chalard Jean05cbe972019-12-09 11:50:38 +09009031 private void processListenRequests(@NonNull final NetworkAgentInfo nai) {
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009032 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
Chalard Jeancd397a22019-11-22 22:33:33 +09009033 processNewlyLostListenRequests(nai);
Chalard Jean05cbe972019-12-09 11:50:38 +09009034 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Chalard Jeancd397a22019-11-22 22:33:33 +09009035 processNewlySatisfiedListenRequests(nai);
9036 }
9037
9038 private void processNewlyLostListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009039 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9040 if (nri.isMultilayerRequest()) {
9041 continue;
9042 }
9043 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009044 if (!nr.isListen()) continue;
9045 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
James Mattisa076c532020-12-02 14:12:41 -08009046 nai.removeRequest(nr.requestId);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009047 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
9048 }
9049 }
Chalard Jeancd397a22019-11-22 22:33:33 +09009050 }
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009051
Chalard Jeancd397a22019-11-22 22:33:33 +09009052 private void processNewlySatisfiedListenRequests(@NonNull final NetworkAgentInfo nai) {
James Mattisa076c532020-12-02 14:12:41 -08009053 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9054 if (nri.isMultilayerRequest()) {
9055 continue;
9056 }
9057 final NetworkRequest nr = nri.mRequests.get(0);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009058 if (!nr.isListen()) continue;
9059 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
9060 nai.addRequest(nr);
Erik Kline99f301b2017-02-15 19:59:17 +09009061 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti0c38d7c2016-07-20 02:39:22 +09009062 }
9063 }
9064 }
9065
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009066 // An accumulator class to gather the list of changes that result from a rematch.
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009067 private static class NetworkReassignment {
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009068 static class RequestReassignment {
James Mattisa076c532020-12-02 14:12:41 -08009069 @NonNull public final NetworkRequestInfo mNetworkRequestInfo;
Chalard Jeana8ac2302021-03-01 22:16:08 +09009070 @Nullable public final NetworkRequest mOldNetworkRequest;
9071 @Nullable public final NetworkRequest mNewNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009072 @Nullable public final NetworkAgentInfo mOldNetwork;
9073 @Nullable public final NetworkAgentInfo mNewNetwork;
James Mattisa076c532020-12-02 14:12:41 -08009074 RequestReassignment(@NonNull final NetworkRequestInfo networkRequestInfo,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009075 @Nullable final NetworkRequest oldNetworkRequest,
9076 @Nullable final NetworkRequest newNetworkRequest,
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009077 @Nullable final NetworkAgentInfo oldNetwork,
9078 @Nullable final NetworkAgentInfo newNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009079 mNetworkRequestInfo = networkRequestInfo;
9080 mOldNetworkRequest = oldNetworkRequest;
9081 mNewNetworkRequest = newNetworkRequest;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009082 mOldNetwork = oldNetwork;
9083 mNewNetwork = newNetwork;
9084 }
Chalard Jean49707572019-12-10 21:07:02 +09009085
9086 public String toString() {
Chalard Jeand490b2d2021-03-01 22:06:04 +09009087 final NetworkRequest requestToShow = null != mNewNetworkRequest
9088 ? mNewNetworkRequest : mNetworkRequestInfo.mRequests.get(0);
9089 return requestToShow.requestId + " : "
Serik Beketayevec8ad212020-12-07 22:43:07 -08009090 + (null != mOldNetwork ? mOldNetwork.network.getNetId() : "null")
9091 + " → " + (null != mNewNetwork ? mNewNetwork.network.getNetId() : "null");
Chalard Jean49707572019-12-10 21:07:02 +09009092 }
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009093 }
9094
Chalard Jean46a62372019-12-10 21:25:24 +09009095 @NonNull private final ArrayList<RequestReassignment> mReassignments = new ArrayList<>();
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009096
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009097 @NonNull Iterable<RequestReassignment> getRequestReassignments() {
Chalard Jean46a62372019-12-10 21:25:24 +09009098 return mReassignments;
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009099 }
9100
9101 void addRequestReassignment(@NonNull final RequestReassignment reassignment) {
Remi NGUYEN VAN10c379a2021-04-07 19:40:31 +09009102 if (Build.isDebuggable()) {
Chalard Jean46a62372019-12-10 21:25:24 +09009103 // The code is never supposed to add two reassignments of the same request. Make
9104 // sure this stays true, but without imposing this expensive check on all
9105 // reassignments on all user devices.
9106 for (final RequestReassignment existing : mReassignments) {
James Mattisa076c532020-12-02 14:12:41 -08009107 if (existing.mNetworkRequestInfo.equals(reassignment.mNetworkRequestInfo)) {
Chalard Jean46a62372019-12-10 21:25:24 +09009108 throw new IllegalStateException("Trying to reassign ["
9109 + reassignment + "] but already have ["
9110 + existing + "]");
9111 }
9112 }
Chalard Jeanbf91f5f2019-12-03 22:16:26 +09009113 }
Chalard Jean46a62372019-12-10 21:25:24 +09009114 mReassignments.add(reassignment);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009115 }
9116
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009117 // Will return null if this reassignment does not change the network assigned to
Chalard Jean8e382112019-12-03 20:45:30 +09009118 // the passed request.
9119 @Nullable
9120 private RequestReassignment getReassignment(@NonNull final NetworkRequestInfo nri) {
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009121 for (final RequestReassignment event : getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009122 if (nri == event.mNetworkRequestInfo) return event;
Chalard Jean88b2f9e2019-12-03 14:43:57 +09009123 }
9124 return null;
9125 }
Chalard Jean49707572019-12-10 21:07:02 +09009126
9127 public String toString() {
9128 final StringJoiner sj = new StringJoiner(", " /* delimiter */,
9129 "NetReassign [" /* prefix */, "]" /* suffix */);
Chalard Jeanb10ab412019-12-11 14:12:30 +09009130 if (mReassignments.isEmpty()) return sj.add("no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009131 for (final RequestReassignment rr : getRequestReassignments()) {
9132 sj.add(rr.toString());
9133 }
9134 return sj.toString();
9135 }
9136
9137 public String debugString() {
9138 final StringBuilder sb = new StringBuilder();
9139 sb.append("NetworkReassignment :");
Chalard Jeanb10ab412019-12-11 14:12:30 +09009140 if (mReassignments.isEmpty()) return sb.append(" no changes").toString();
Chalard Jean49707572019-12-10 21:07:02 +09009141 for (final RequestReassignment rr : getRequestReassignments()) {
9142 sb.append("\n ").append(rr);
9143 }
9144 return sb.append("\n").toString();
9145 }
Chalard Jean9fc27ea2019-12-02 15:34:05 +09009146 }
9147
Chalard Jean24344d72019-12-04 13:32:31 +09009148 private void updateSatisfiersForRematchRequest(@NonNull final NetworkRequestInfo nri,
Chalard Jeana8ac2302021-03-01 22:16:08 +09009149 @Nullable final NetworkRequest previousRequest,
9150 @Nullable final NetworkRequest newRequest,
Chalard Jean24344d72019-12-04 13:32:31 +09009151 @Nullable final NetworkAgentInfo previousSatisfier,
9152 @Nullable final NetworkAgentInfo newSatisfier,
9153 final long now) {
James Mattisd31bdfa2020-12-23 16:37:26 -08009154 if (null != newSatisfier && mNoServiceNetwork != newSatisfier) {
Chalard Jean49707572019-12-10 21:07:02 +09009155 if (VDBG) log("rematch for " + newSatisfier.toShortString());
Chalard Jeana8ac2302021-03-01 22:16:08 +09009156 if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009157 if (VDBG || DDBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009158 log(" accepting network in place of " + previousSatisfier.toShortString());
Chalard Jean24344d72019-12-04 13:32:31 +09009159 }
James Mattisa076c532020-12-02 14:12:41 -08009160 previousSatisfier.removeRequest(previousRequest.requestId);
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009161 if (canSupportGracefulNetworkSwitch(previousSatisfier, newSatisfier)
Chalard Jean254bd162022-08-25 13:04:51 +09009162 && !previousSatisfier.isDestroyed()) {
Chalard Jean0702f982021-09-16 21:50:07 +09009163 // If this network switch can't be supported gracefully, the request is not
9164 // lingered. This allows letting go of the network sooner to reclaim some
9165 // performance on the new network, since the radio can't do both at the same
9166 // time while preserving good performance.
Lorenzo Colittiffa2ed32022-02-16 14:59:00 +09009167 //
9168 // Also don't linger the request if the old network has been destroyed.
9169 // A destroyed network does not provide actual network connectivity, so
9170 // lingering it is not useful. In particular this ensures that a destroyed
9171 // network is outscored by its replacement,
9172 // then it is torn down immediately instead of being lingered, and any apps that
9173 // were using it immediately get onLost and can connect using the new network.
Chalard Jean0702f982021-09-16 21:50:07 +09009174 previousSatisfier.lingerRequest(previousRequest.requestId, now);
9175 }
Chalard Jean24344d72019-12-04 13:32:31 +09009176 } else {
9177 if (VDBG || DDBG) log(" accepting network in place of null");
9178 }
junyulai0ac374f2020-12-14 18:41:52 +08009179
9180 // To prevent constantly CPU wake up for nascent timer, if a network comes up
9181 // and immediately satisfies a request then remove the timer. This will happen for
9182 // all networks except in the case of an underlying network for a VCN.
9183 if (newSatisfier.isNascent()) {
9184 newSatisfier.unlingerRequest(NetworkRequest.REQUEST_ID_NONE);
junyulai36c02982021-03-26 00:40:48 +08009185 newSatisfier.unsetInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009186 }
9187
Chalard Jean5d6e23b2021-03-01 22:00:20 +09009188 // if newSatisfier is not null, then newRequest may not be null.
James Mattisa076c532020-12-02 14:12:41 -08009189 newSatisfier.unlingerRequest(newRequest.requestId);
9190 if (!newSatisfier.addRequest(newRequest)) {
Aaron Huang6616df32020-10-30 22:04:25 +08009191 Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
James Mattisa076c532020-12-02 14:12:41 -08009192 + newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009193 }
Chalard Jeana8ac2302021-03-01 22:16:08 +09009194 } else if (null != previousRequest && null != previousSatisfier) {
Chalard Jean24344d72019-12-04 13:32:31 +09009195 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009196 log("Network " + previousSatisfier.toShortString() + " stopped satisfying"
James Mattisa076c532020-12-02 14:12:41 -08009197 + " request " + previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009198 }
James Mattisa076c532020-12-02 14:12:41 -08009199 previousSatisfier.removeRequest(previousRequest.requestId);
Chalard Jean24344d72019-12-04 13:32:31 +09009200 }
James Mattisa076c532020-12-02 14:12:41 -08009201 nri.setSatisfier(newSatisfier, newRequest);
Chalard Jean24344d72019-12-04 13:32:31 +09009202 }
9203
James Mattisa076c532020-12-02 14:12:41 -08009204 /**
9205 * This function is triggered when something can affect what network should satisfy what
9206 * request, and it computes the network reassignment from the passed collection of requests to
9207 * network match to the one that the system should now have. That data is encoded in an
9208 * object that is a list of changes, each of them having an NRI, and old satisfier, and a new
9209 * satisfier.
9210 *
9211 * After the reassignment is computed, it is applied to the state objects.
9212 *
9213 * @param networkRequests the nri objects to evaluate for possible network reassignment
9214 * @return NetworkReassignment listing of proposed network assignment changes
9215 */
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009216 @NonNull
James Mattisa076c532020-12-02 14:12:41 -08009217 private NetworkReassignment computeNetworkReassignment(
9218 @NonNull final Collection<NetworkRequestInfo> networkRequests) {
Chalard Jean857a1712019-12-10 21:08:07 +09009219 final NetworkReassignment changes = new NetworkReassignment();
9220
Chalard Jeanc81d4c32021-04-07 17:06:19 +09009221 // Gather the list of all relevant agents.
Chalard Jean857a1712019-12-10 21:08:07 +09009222 final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009223 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean857a1712019-12-10 21:08:07 +09009224 nais.add(nai);
Chalard Jean857a1712019-12-10 21:08:07 +09009225 }
Chalard Jean857a1712019-12-10 21:08:07 +09009226
James Mattisa076c532020-12-02 14:12:41 -08009227 for (final NetworkRequestInfo nri : networkRequests) {
9228 // Non-multilayer listen requests can be ignored.
9229 if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
9230 continue;
9231 }
9232 NetworkAgentInfo bestNetwork = null;
9233 NetworkRequest bestRequest = null;
9234 for (final NetworkRequest req : nri.mRequests) {
Chalard Jeane4aeac62021-03-29 17:03:59 +09009235 bestNetwork = mNetworkRanker.getBestNetwork(req, nais, nri.getSatisfier());
James Mattisa076c532020-12-02 14:12:41 -08009236 // Stop evaluating as the highest possible priority request is satisfied.
9237 if (null != bestNetwork) {
9238 bestRequest = req;
9239 break;
9240 }
9241 }
James Mattisd31bdfa2020-12-23 16:37:26 -08009242 if (null == bestNetwork && isDefaultBlocked(nri)) {
9243 // Remove default networking if disallowed for managed default requests.
9244 bestNetwork = mNoServiceNetwork;
9245 }
9246 if (nri.getSatisfier() != bestNetwork) {
Chalard Jean96a4f4b2019-12-10 22:16:53 +09009247 // bestNetwork may be null if no network can satisfy this request.
Chalard Jean857a1712019-12-10 21:08:07 +09009248 changes.addRequestReassignment(new NetworkReassignment.RequestReassignment(
James Mattisa076c532020-12-02 14:12:41 -08009249 nri, nri.mActiveRequest, bestRequest, nri.getSatisfier(), bestNetwork));
Chalard Jean857a1712019-12-10 21:08:07 +09009250 }
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009251 }
9252 return changes;
9253 }
9254
James Mattisa076c532020-12-02 14:12:41 -08009255 private Set<NetworkRequestInfo> getNrisFromGlobalRequests() {
9256 return new HashSet<>(mNetworkRequests.values());
9257 }
9258
Paul Jensenc88b39b2015-06-16 14:27:36 -04009259 /**
James Mattisa076c532020-12-02 14:12:41 -08009260 * Attempt to rematch all Networks with all NetworkRequests. This may result in Networks
Paul Jensenc88b39b2015-06-16 14:27:36 -04009261 * being disconnected.
Paul Jensenc88b39b2015-06-16 14:27:36 -04009262 */
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009263 private void rematchAllNetworksAndRequests() {
James Mattisa076c532020-12-02 14:12:41 -08009264 rematchNetworksAndRequests(getNrisFromGlobalRequests());
9265 }
9266
9267 /**
9268 * Attempt to rematch all Networks with given NetworkRequests. This may result in Networks
9269 * being disconnected.
9270 */
9271 private void rematchNetworksAndRequests(
9272 @NonNull final Set<NetworkRequestInfo> networkRequests) {
9273 ensureRunningOnConnectivityServiceThread();
Chalard Jean857a1712019-12-10 21:08:07 +09009274 // TODO: This may be slow, and should be optimized.
Chalard Jeanee3fa202022-02-26 13:55:15 +09009275 final long start = SystemClock.elapsedRealtime();
James Mattisa076c532020-12-02 14:12:41 -08009276 final NetworkReassignment changes = computeNetworkReassignment(networkRequests);
Chalard Jeanee3fa202022-02-26 13:55:15 +09009277 final long computed = SystemClock.elapsedRealtime();
9278 applyNetworkReassignment(changes, start);
9279 final long applied = SystemClock.elapsedRealtime();
9280 issueNetworkNeeds();
9281 final long end = SystemClock.elapsedRealtime();
Chalard Jean49707572019-12-10 21:07:02 +09009282 if (VDBG || DDBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009283 log(String.format("Rematched networks [computed %dms] [applied %dms] [issued %d]",
9284 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009285 log(changes.debugString());
9286 } else if (DBG) {
Chalard Jeanee3fa202022-02-26 13:55:15 +09009287 // Shorter form, only one line of log
9288 log(String.format("%s [c %d] [a %d] [i %d]", changes.toString(),
9289 computed - start, applied - computed, end - applied));
Chalard Jean49707572019-12-10 21:07:02 +09009290 }
Chalard Jeand7f762d2019-12-10 19:01:29 +09009291 }
Chalard Jean64520dc2019-12-04 19:55:32 +09009292
Chalard Jeand7f762d2019-12-10 19:01:29 +09009293 private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
Chalard Jeanf955f8e2019-12-10 22:01:31 +09009294 final long now) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009295 final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
Chalard Jeanb10ab412019-12-11 14:12:30 +09009296
9297 // Since most of the time there are only 0 or 1 background networks, it would probably
9298 // be more efficient to just use an ArrayList here. TODO : measure performance
9299 final ArraySet<NetworkAgentInfo> oldBgNetworks = new ArraySet<>();
9300 for (final NetworkAgentInfo nai : nais) {
9301 if (nai.isBackgroundNetwork()) oldBgNetworks.add(nai);
9302 }
9303
Chalard Jeand7f762d2019-12-10 19:01:29 +09009304 // First, update the lists of satisfied requests in the network agents. This is necessary
9305 // because some code later depends on this state to be correct, most prominently computing
9306 // the linger status.
Chalard Jean64520dc2019-12-04 19:55:32 +09009307 for (final NetworkReassignment.RequestReassignment event :
9308 changes.getRequestReassignments()) {
James Mattisa076c532020-12-02 14:12:41 -08009309 updateSatisfiersForRematchRequest(event.mNetworkRequestInfo,
9310 event.mOldNetworkRequest, event.mNewNetworkRequest,
9311 event.mOldNetwork, event.mNewNetwork,
9312 now);
Chalard Jean0a8afda2019-11-07 19:05:18 +09009313 }
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009314
James Mattise3ef1912020-12-20 11:09:58 -08009315 // Process default network changes if applicable.
9316 processDefaultNetworkChanges(changes);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009317
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009318 // Notify requested networks are available after the default net is switched, but
9319 // before LegacyTypeTracker sends legacy broadcasts
9320 for (final NetworkReassignment.RequestReassignment event :
9321 changes.getRequestReassignments()) {
9322 if (null != event.mNewNetwork) {
James Mattisa076c532020-12-02 14:12:41 -08009323 notifyNetworkAvailable(event.mNewNetwork, event.mNetworkRequestInfo);
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009324 } else {
James Mattisa076c532020-12-02 14:12:41 -08009325 callCallbackForRequest(event.mNetworkRequestInfo, event.mOldNetwork,
Chalard Jean7c2f15e2019-12-03 15:55:14 +09009326 ConnectivityManager.CALLBACK_LOST, 0);
Chalard Jeand8bea3b2019-12-02 18:59:27 +09009327 }
9328 }
9329
junyulai0ac374f2020-12-14 18:41:52 +08009330 // Update the inactivity state before processing listen callbacks, because the background
9331 // computation depends on whether the network is inactive. Don't send the LOSING callbacks
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009332 // just yet though, because they have to be sent after the listens are processed to keep
9333 // backward compatibility.
junyulai0ac374f2020-12-14 18:41:52 +08009334 final ArrayList<NetworkAgentInfo> inactiveNetworks = new ArrayList<>();
Chalard Jean7807fa22019-11-19 20:01:10 +09009335 for (final NetworkAgentInfo nai : nais) {
junyulai0ac374f2020-12-14 18:41:52 +08009336 // Rematching may have altered the inactivity state of some networks, so update all
9337 // inactivity timers. updateInactivityState reads the state from the network agent
9338 // and does nothing if the state has not changed : the source of truth is controlled
9339 // with NetworkAgentInfo#lingerRequest and NetworkAgentInfo#unlingerRequest, which
9340 // have been called while rematching the individual networks above.
junyulai2b6f0c22021-02-03 20:15:30 +08009341 if (updateInactivityState(nai, now)) {
junyulai0ac374f2020-12-14 18:41:52 +08009342 inactiveNetworks.add(nai);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009343 }
9344 }
9345
Chalard Jeanb10ab412019-12-11 14:12:30 +09009346 for (final NetworkAgentInfo nai : nais) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009347 final boolean oldBackground = oldBgNetworks.contains(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009348 // Process listen requests and update capabilities if the background state has
9349 // changed for this network. For consistency with previous behavior, send onLost
9350 // callbacks before onAvailable.
Chalard Jeanb10ab412019-12-11 14:12:30 +09009351 processNewlyLostListenRequests(nai);
9352 if (oldBackground != nai.isBackgroundNetwork()) {
9353 applyBackgroundChangeForRematch(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009354 }
Chalard Jeanb10ab412019-12-11 14:12:30 +09009355 processNewlySatisfiedListenRequests(nai);
Chalard Jean6a4dfac2019-12-04 20:01:46 +09009356 }
9357
junyulai0ac374f2020-12-14 18:41:52 +08009358 for (final NetworkAgentInfo nai : inactiveNetworks) {
9359 // For nascent networks, if connecting with no foreground request, skip broadcasting
9360 // LOSING for backward compatibility. This is typical when mobile data connected while
9361 // wifi connected with mobile data always-on enabled.
9362 if (nai.isNascent()) continue;
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009363 notifyNetworkLosing(nai, now);
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009364 }
9365
James Mattise3ef1912020-12-20 11:09:58 -08009366 updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
Chalard Jeanf0344532019-11-19 19:23:38 +09009367
Chalard Jeanf01b2ef2019-11-07 23:16:12 +09009368 // Tear down all unneeded networks.
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009369 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009370 if (unneeded(nai, UnneededFor.TEARDOWN)) {
junyulai2b6f0c22021-02-03 20:15:30 +08009371 if (nai.getInactivityExpiry() > 0) {
Chalard Jean0a8afda2019-11-07 19:05:18 +09009372 // This network has active linger timers and no requests, but is not
9373 // lingering. Linger it.
9374 //
9375 // One way (the only way?) this can happen if this network is unvalidated
9376 // and became unneeded due to another network improving its score to the
9377 // point where this network will no longer be able to satisfy any requests
9378 // even if it validates.
junyulai2b6f0c22021-02-03 20:15:30 +08009379 if (updateInactivityState(nai, now)) {
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009380 notifyNetworkLosing(nai, now);
9381 }
Chalard Jean0a8afda2019-11-07 19:05:18 +09009382 } else {
Chalard Jean49707572019-12-10 21:07:02 +09009383 if (DBG) log("Reaping " + nai.toShortString());
Chalard Jean0a8afda2019-11-07 19:05:18 +09009384 teardownUnneededNetwork(nai);
9385 }
9386 }
Paul Jensen05e85ee2014-09-11 11:00:39 -04009387 }
9388 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009389
Chalard Jean62edfd82019-12-02 18:39:29 +09009390 /**
9391 * Apply a change in background state resulting from rematching networks with requests.
9392 *
9393 * During rematch, a network may change background states by starting to satisfy or stopping
9394 * to satisfy a foreground request. Listens don't count for this. When a network changes
9395 * background states, its capabilities need to be updated and callbacks fired for the
9396 * capability change.
9397 *
9398 * @param nai The network that changed background states
9399 */
9400 private void applyBackgroundChangeForRematch(@NonNull final NetworkAgentInfo nai) {
9401 final NetworkCapabilities newNc = mixInCapabilities(nai, nai.networkCapabilities);
9402 if (Objects.equals(nai.networkCapabilities, newNc)) return;
9403 updateNetworkPermissions(nai, newNc);
9404 nai.getAndSetNetworkCapabilities(newNc);
9405 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
9406 }
9407
Chalard Jeanf0344532019-11-19 19:23:38 +09009408 private void updateLegacyTypeTrackerAndVpnLockdownForRematch(
James Mattise3ef1912020-12-20 11:09:58 -08009409 @NonNull final NetworkReassignment changes,
Chalard Jean57cc7cb2019-12-10 18:56:30 +09009410 @NonNull final Collection<NetworkAgentInfo> nais) {
Chalard Jean5b409c72021-02-04 13:12:59 +09009411 final NetworkReassignment.RequestReassignment reassignmentOfDefault =
9412 changes.getReassignment(mDefaultRequest);
9413 final NetworkAgentInfo oldDefaultNetwork =
9414 null != reassignmentOfDefault ? reassignmentOfDefault.mOldNetwork : null;
9415 final NetworkAgentInfo newDefaultNetwork =
9416 null != reassignmentOfDefault ? reassignmentOfDefault.mNewNetwork : null;
James Mattise3ef1912020-12-20 11:09:58 -08009417
Chalard Jean5b409c72021-02-04 13:12:59 +09009418 if (oldDefaultNetwork != newDefaultNetwork) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009419 // Maintain the illusion : since the legacy API only understands one network at a time,
9420 // if the default network changed, apps should see a disconnected broadcast for the
9421 // old default network before they see a connected broadcast for the new one.
Chalard Jean5b409c72021-02-04 13:12:59 +09009422 if (oldDefaultNetwork != null) {
9423 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
9424 oldDefaultNetwork, true);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009425 }
Chalard Jean5b409c72021-02-04 13:12:59 +09009426 if (newDefaultNetwork != null) {
Chalard Jeanb9d94052019-11-19 19:16:48 +09009427 // The new default network can be newly null if and only if the old default
9428 // network doesn't satisfy the default request any more because it lost a
9429 // capability.
Chalard Jean254bd162022-08-25 13:04:51 +09009430 mDefaultInetConditionPublished = newDefaultNetwork.isValidated() ? 100 : 0;
James Mattise3ef1912020-12-20 11:09:58 -08009431 mLegacyTypeTracker.add(
Chalard Jean5b409c72021-02-04 13:12:59 +09009432 newDefaultNetwork.networkInfo.getType(), newDefaultNetwork);
Chalard Jeanb9d94052019-11-19 19:16:48 +09009433 }
9434 }
9435
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009436 // Now that all the callbacks have been sent, send the legacy network broadcasts
9437 // as needed. This is necessary so that legacy requests correctly bind dns
9438 // requests to this network. The legacy users are listening for this broadcast
9439 // and will generally do a dns request so they can ensureRouteToHost and if
9440 // they do that before the callbacks happen they'll use the default network.
9441 //
9442 // TODO: Is there still a race here? The legacy broadcast will be sent after sending
9443 // callbacks, but if apps can receive the broadcast before the callback, they still might
9444 // have an inconsistent view of networking.
9445 //
9446 // This *does* introduce a race where if the user uses the new api
9447 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
9448 // they may get old info. Reverse this after the old startUsing api is removed.
9449 // This is on top of the multiple intent sequencing referenced in the todo above.
9450 for (NetworkAgentInfo nai : nais) {
Chalard Jean254bd162022-08-25 13:04:51 +09009451 if (nai.everConnected()) {
Chalard Jeanb10ab412019-12-11 14:12:30 +09009452 addNetworkToLegacyTypeTracker(nai);
9453 }
The Android Open Source Project28527d22009-03-03 19:31:44 -08009454 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009455 }
9456
Chalard Jean0354d8c2021-01-12 10:58:56 +09009457 private void issueNetworkNeeds() {
9458 ensureRunningOnConnectivityServiceThread();
9459 for (final NetworkOfferInfo noi : mNetworkOffers) {
9460 issueNetworkNeeds(noi);
9461 }
9462 }
9463
9464 private void issueNetworkNeeds(@NonNull final NetworkOfferInfo noi) {
9465 ensureRunningOnConnectivityServiceThread();
9466 for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
9467 informOffer(nri, noi.offer, mNetworkRanker);
9468 }
9469 }
9470
9471 /**
9472 * Inform a NetworkOffer about any new situation of a request.
9473 *
9474 * This function handles updates to offers. A number of events may happen that require
9475 * updating the registrant for this offer about the situation :
9476 * • The offer itself was updated. This may lead the offer to no longer being able
9477 * to satisfy a request or beat a satisfier (and therefore be no longer needed),
9478 * or conversely being strengthened enough to beat the satisfier (and therefore
9479 * start being needed)
9480 * • The network satisfying a request changed (including cases where the request
9481 * starts or stops being satisfied). The new network may be a stronger or weaker
9482 * match than the old one, possibly affecting whether the offer is needed.
9483 * • The network satisfying a request updated their score. This may lead the offer
9484 * to no longer be able to beat it if the current satisfier got better, or
9485 * conversely start being a good choice if the current satisfier got weaker.
9486 *
9487 * @param nri The request
9488 * @param offer The offer. This may be an updated offer.
9489 */
9490 private static void informOffer(@NonNull NetworkRequestInfo nri,
9491 @NonNull final NetworkOffer offer, @NonNull final NetworkRanker networkRanker) {
9492 final NetworkRequest activeRequest = nri.isBeingSatisfied() ? nri.getActiveRequest() : null;
9493 final NetworkAgentInfo satisfier = null != activeRequest ? nri.getSatisfier() : null;
Chalard Jean0354d8c2021-01-12 10:58:56 +09009494
9495 // Multi-layer requests have a currently active request, the one being satisfied.
9496 // Since the system will try to bring up a better network than is currently satisfying
9497 // the request, NetworkProviders need to be told the offers matching the requests *above*
9498 // the currently satisfied one are needed, that the ones *below* the satisfied one are
9499 // not needed, and the offer is needed for the active request iff the offer can beat
9500 // the satisfier.
9501 // For non-multilayer requests, the logic above gracefully degenerates to only the
9502 // last case.
9503 // To achieve this, the loop below will proceed in three steps. In a first phase, inform
9504 // providers that the offer is needed for this request, until the active request is found.
9505 // In a second phase, deal with the currently active request. In a third phase, inform
9506 // the providers that offer is unneeded for the remaining requests.
9507
9508 // First phase : inform providers of all requests above the active request.
9509 int i;
9510 for (i = 0; nri.mRequests.size() > i; ++i) {
9511 final NetworkRequest request = nri.mRequests.get(i);
9512 if (activeRequest == request) break; // Found the active request : go to phase 2
9513 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9514 // Since this request is higher-priority than the one currently satisfied, if the
9515 // offer can satisfy it, the provider should try and bring up the network for sure ;
9516 // no need to even ask the ranker – an offer that can satisfy is always better than
9517 // no network. Hence tell the provider so unless it already knew.
9518 if (request.canBeSatisfiedBy(offer.caps) && !offer.neededFor(request)) {
9519 offer.onNetworkNeeded(request);
9520 }
9521 }
9522
9523 // Second phase : deal with the active request (if any)
9524 if (null != activeRequest && activeRequest.isRequest()) {
9525 final boolean oldNeeded = offer.neededFor(activeRequest);
Junyu Laidc3a7a32021-05-26 12:23:56 +00009526 // If an offer can satisfy the request, it is considered needed if it is currently
9527 // served by this provider or if this offer can beat the current satisfier.
Chalard Jean0354d8c2021-01-12 10:58:56 +09009528 final boolean currentlyServing = satisfier != null
Junyu Laidc3a7a32021-05-26 12:23:56 +00009529 && satisfier.factorySerialNumber == offer.providerId
9530 && activeRequest.canBeSatisfiedBy(offer.caps);
9531 final boolean newNeeded = currentlyServing
9532 || networkRanker.mightBeat(activeRequest, satisfier, offer);
Chalard Jean0354d8c2021-01-12 10:58:56 +09009533 if (newNeeded != oldNeeded) {
9534 if (newNeeded) {
9535 offer.onNetworkNeeded(activeRequest);
9536 } else {
9537 // The offer used to be able to beat the satisfier. Now it can't.
9538 offer.onNetworkUnneeded(activeRequest);
9539 }
9540 }
9541 }
9542
9543 // Third phase : inform the providers that the offer isn't needed for any request
9544 // below the active one.
9545 for (++i /* skip the active request */; nri.mRequests.size() > i; ++i) {
9546 final NetworkRequest request = nri.mRequests.get(i);
9547 if (!request.isRequest()) continue; // Listens/track defaults are never sent to offers
9548 // Since this request is lower-priority than the one currently satisfied, if the
9549 // offer can satisfy it, the provider should not try and bring up the network.
9550 // Hence tell the provider so unless it already knew.
9551 if (offer.neededFor(request)) {
9552 offer.onNetworkUnneeded(request);
9553 }
9554 }
9555 }
9556
Chalard Jean61c79252019-11-07 23:07:32 +09009557 private void addNetworkToLegacyTypeTracker(@NonNull final NetworkAgentInfo nai) {
9558 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9559 NetworkRequest nr = nai.requestAt(i);
9560 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
9561 // legacy type tracker filters out repeat adds
9562 mLegacyTypeTracker.add(nr.legacyType, nai);
9563 }
9564 }
9565
9566 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
Chalard Jean5b409c72021-02-04 13:12:59 +09009567 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
Chalard Jean61c79252019-11-07 23:07:32 +09009568 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
9569 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
9570 if (nai.isVPN()) {
9571 mLegacyTypeTracker.add(TYPE_VPN, nai);
9572 }
9573 }
9574
Lorenzo Colitti5f82dae2014-12-17 11:26:49 +09009575 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensen39fc7d52014-09-05 12:06:44 -04009576 // Don't bother updating until we've graduated to validated at least once.
Chalard Jean254bd162022-08-25 13:04:51 +09009577 if (!nai.everValidated()) return;
Chalard Jean5b409c72021-02-04 13:12:59 +09009578 // For now only update icons for the default connection.
Paul Jensen39fc7d52014-09-05 12:06:44 -04009579 // TODO: Update WiFi and cellular icons separately. b/17237507
Chalard Jean5b409c72021-02-04 13:12:59 +09009580 if (!isDefaultNetwork(nai)) return;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009581
Chalard Jean254bd162022-08-25 13:04:51 +09009582 int newInetCondition = nai.isValidated() ? 100 : 0;
Paul Jensen39fc7d52014-09-05 12:06:44 -04009583 // Don't repeat publish.
9584 if (newInetCondition == mDefaultInetConditionPublished) return;
9585
9586 mDefaultInetConditionPublished = newInetCondition;
9587 sendInetConditionBroadcast(nai.networkInfo);
9588 }
9589
Chalard Jeand61375d2020-01-14 22:46:36 +09009590 @NonNull
9591 private NetworkInfo mixInInfo(@NonNull final NetworkAgentInfo nai, @NonNull NetworkInfo info) {
9592 final NetworkInfo newInfo = new NetworkInfo(info);
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009593 // The suspended and roaming bits are managed in NetworkCapabilities.
Chalard Jeand61375d2020-01-14 22:46:36 +09009594 final boolean suspended =
9595 !nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_SUSPENDED);
9596 if (suspended && info.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
9597 // Only override the state with SUSPENDED if the network is currently in CONNECTED
9598 // state. This is because the network could have been suspended before connecting,
9599 // or it could be disconnecting while being suspended, and in both these cases
9600 // the state should not be overridden. Note that the only detailed state that
9601 // maps to State.CONNECTED is DetailedState.CONNECTED, so there is also no need to
9602 // worry about multiple different substates of CONNECTED.
9603 newInfo.setDetailedState(NetworkInfo.DetailedState.SUSPENDED, info.getReason(),
9604 info.getExtraInfo());
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009605 } else if (!suspended && info.getDetailedState() == NetworkInfo.DetailedState.SUSPENDED) {
9606 // SUSPENDED state is currently only overridden from CONNECTED state. In the case the
9607 // network agent is created, then goes to suspended, then goes out of suspended without
9608 // ever setting connected. Check if network agent is ever connected to update the state.
Chalard Jean254bd162022-08-25 13:04:51 +09009609 newInfo.setDetailedState(nai.everConnected()
Chiachang Wangaa88bca2020-02-12 17:01:59 +08009610 ? NetworkInfo.DetailedState.CONNECTED
9611 : NetworkInfo.DetailedState.CONNECTING,
9612 info.getReason(),
9613 info.getExtraInfo());
Chalard Jeand61375d2020-01-14 22:46:36 +09009614 }
Chalard Jeanaf14ca42020-01-15 00:49:43 +09009615 newInfo.setRoaming(!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING));
Chalard Jeand61375d2020-01-14 22:46:36 +09009616 return newInfo;
9617 }
9618
9619 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo info) {
9620 final NetworkInfo newInfo = mixInInfo(networkAgent, info);
9621
Erik Kline99f301b2017-02-15 19:59:17 +09009622 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt02fe11e2014-06-23 11:40:00 -07009623 NetworkInfo oldInfo = null;
9624 synchronized (networkAgent) {
9625 oldInfo = networkAgent.networkInfo;
9626 networkAgent.networkInfo = newInfo;
9627 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009628
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009629 if (DBG) {
Chalard Jean49707572019-12-10 21:07:02 +09009630 log(networkAgent.toShortString() + " EVENT_NETWORK_INFO_CHANGED, going from "
9631 + oldInfo.getState() + " to " + state);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009632 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009633
Chalard Jean254bd162022-08-25 13:04:51 +09009634 if (!networkAgent.isCreated()
Robin Leea8c0b6e2016-05-01 23:00:00 +01009635 && (state == NetworkInfo.State.CONNECTED
9636 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colitti0f042202016-07-18 18:40:42 +09009637
9638 // A network that has just connected has zero requests and is thus a foreground network.
9639 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
9640
Luke Huangfdd11f82019-04-09 18:41:49 +08009641 if (!createNativeNetwork(networkAgent)) return;
Lorenzo Colittibd079452021-07-02 11:47:57 +09009642 if (networkAgent.propagateUnderlyingCapabilities()) {
Lorenzo Colitti96dba632020-12-02 00:48:09 +09009643 // Initialize the network's capabilities to their starting values according to the
9644 // underlying networks. This ensures that the capabilities are correct before
9645 // anything happens to the network.
9646 updateCapabilitiesForNetwork(networkAgent);
Chalard Jeand5687912020-05-07 12:07:03 +09009647 }
Chalard Jean254bd162022-08-25 13:04:51 +09009648 networkAgent.setCreated();
Chiachang Wang3f6cc072021-03-24 18:39:17 +08009649 networkAgent.onNetworkCreated();
Chalard Jeande665262022-02-25 16:12:12 +09009650 updateAllowedUids(networkAgent, null, networkAgent.networkCapabilities);
Junyu Lai35665cc2022-12-19 17:37:48 +08009651 updateProfileAllowedNetworks();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009652 }
9653
Chalard Jean254bd162022-08-25 13:04:51 +09009654 if (!networkAgent.everConnected() && state == NetworkInfo.State.CONNECTED) {
9655 networkAgent.setConnected();
Robin Leea8c0b6e2016-05-01 23:00:00 +01009656
lucaslin45e639b2019-04-03 17:09:28 +08009657 // NetworkCapabilities need to be set before sending the private DNS config to
9658 // NetworkMonitor, otherwise NetworkMonitor cannot determine if validation is required.
Chalard Jean05edd052019-11-22 22:39:56 +09009659 networkAgent.getAndSetNetworkCapabilities(networkAgent.networkCapabilities);
9660
Erik Kline9a62f012018-03-21 07:18:33 -07009661 handlePerNetworkPrivateDnsConfig(networkAgent, mDnsManager.getPrivateDnsConfig());
lucaslin74fa3972018-11-28 12:51:55 +08009662 updateLinkProperties(networkAgent, new LinkProperties(networkAgent.linkProperties),
9663 null);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009664
Patrick Rohrf1fe8ee2022-03-02 15:14:07 +01009665 // If a rate limit has been configured and is applicable to this network (network
9666 // provides internet connectivity), apply it. The tc police filter cannot be attached
9667 // before the clsact qdisc is added which happens as part of updateLinkProperties ->
9668 // updateInterfaces -> INetd#networkAddInterface.
9669 // Note: in case of a system server crash, the NetworkController constructor in netd
9670 // (called when netd starts up) deletes the clsact qdisc of all interfaces.
9671 if (canNetworkBeRateLimited(networkAgent) && mIngressRateLimit >= 0) {
9672 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
9673 mIngressRateLimit);
9674 }
9675
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009676 // Until parceled LinkProperties are sent directly to NetworkMonitor, the connect
9677 // command must be sent after updating LinkProperties to maximize chances of
9678 // NetworkMonitor seeing the correct LinkProperties when starting.
9679 // TODO: pass LinkProperties to the NetworkMonitor in the notifyNetworkConnected call.
Lorenzo Colittiab2fed72020-01-12 22:28:37 +09009680 if (networkAgent.networkAgentConfig.acceptPartialConnectivity) {
Lorenzo Colitti6edf86c2019-05-31 15:41:29 +09009681 networkAgent.networkMonitor().setAcceptPartialConnectivity();
Remi NGUYEN VAN85391292018-12-27 16:43:56 +09009682 }
Chalard Jeand4900722022-02-06 12:25:38 +09009683 final NetworkMonitorParameters params = new NetworkMonitorParameters();
9684 params.networkAgentConfig = networkAgent.networkAgentConfig;
9685 params.networkCapabilities = networkAgent.networkCapabilities;
9686 params.linkProperties = new LinkProperties(networkAgent.linkProperties,
9687 true /* parcelSensitiveFields */);
Remi NGUYEN VAN9ada1842022-05-31 11:17:02 +09009688 // isAtLeastT() is conservative here, as recent versions of NetworkStack support the
9689 // newer callback even before T. However getInterfaceVersion is a synchronized binder
9690 // call that would cause a Log.wtf to be emitted from the system_server process, and
9691 // in the absence of a satisfactory, scalable solution which follows an easy/standard
9692 // process to check the interface version, just use an SDK check. NetworkStack will
9693 // always be new enough when running on T+.
9694 if (SdkLevel.isAtLeastT()) {
9695 networkAgent.networkMonitor().notifyNetworkConnected(params);
9696 } else {
9697 networkAgent.networkMonitor().notifyNetworkConnected(params.linkProperties,
9698 params.networkCapabilities);
9699 }
Chalard Jeane63c42f2022-09-16 19:31:45 +09009700 final long delay = activelyPreferBadWifi()
9701 ? ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS
9702 : DONT_ACTIVELY_PREFER_BAD_WIFI_INITIAL_TIMEOUT_MS;
9703 scheduleEvaluationTimeout(networkAgent.network, delay);
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009704
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009705 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
9706 // be communicated to a particular NetworkAgent depends only on the network's immutable,
9707 // capabilities, so it only needs to be done once on initial connect, not every time the
9708 // network's capabilities change. Note that we do this before rematching the network,
9709 // so we could decide to tear it down immediately afterwards. That's fine though - on
9710 // disconnection NetworkAgents should stop any signal strength monitoring they have been
9711 // doing.
Lorenzo Colitti0a6477e2015-09-15 15:56:01 +09009712 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colitti5d2656c2015-07-06 23:50:27 +09009713
junyulai0ac374f2020-12-14 18:41:52 +08009714 // Before first rematching networks, put an inactivity timer without any request, this
9715 // allows {@code updateInactivityState} to update the state accordingly and prevent
9716 // tearing down for any {@code unneeded} evaluation in this period.
9717 // Note that the timer will not be rescheduled since the expiry time is
9718 // fixed after connection regardless of the network satisfying other requests or not.
9719 // But it will be removed as soon as the network satisfies a request for the first time.
9720 networkAgent.lingerRequest(NetworkRequest.REQUEST_ID_NONE,
9721 SystemClock.elapsedRealtime(), mNascentDelayMs);
junyulai36c02982021-03-26 00:40:48 +08009722 networkAgent.setInactive();
junyulai0ac374f2020-12-14 18:41:52 +08009723
Paul Jensen05e85ee2014-09-11 11:00:39 -04009724 // Consider network even though it is not yet validated.
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009725 rematchAllNetworksAndRequests();
Lorenzo Colitti0f6d6bd2015-04-09 14:35:26 +09009726
9727 // This has to happen after matching the requests, because callbacks are just requests.
9728 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009729 } else if (state == NetworkInfo.State.DISCONNECTED) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009730 networkAgent.disconnect();
Paul Jensen8b5fc622014-05-07 15:27:40 -04009731 if (networkAgent.isVPN()) {
Lorenzo Colitti96a3f142022-02-08 16:21:01 +00009732 updateVpnUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen8b5fc622014-05-07 15:27:40 -04009733 }
Chalard Jeand9fffc32018-05-11 20:19:20 +09009734 disconnectAndDestroyNetwork(networkAgent);
Irina Dumitrescude132bb2018-12-05 16:19:47 +00009735 if (networkAgent.isVPN()) {
9736 // As the active or bound network changes for apps, broadcast the default proxy, as
9737 // apps may need to update their proxy data. This is called after disconnecting from
9738 // VPN to make sure we do not broadcast the old proxy data.
9739 // TODO(b/122649188): send the broadcast only to VPN users.
9740 mProxyTracker.sendProxyBroadcast();
9741 }
Chalard Jean254bd162022-08-25 13:04:51 +09009742 } else if (networkAgent.isCreated() && (oldInfo.getState() == NetworkInfo.State.SUSPENDED
9743 || state == NetworkInfo.State.SUSPENDED)) {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009744 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009745 }
9746 }
9747
Chalard Jean28018572020-12-21 18:36:52 +09009748 private void updateNetworkScore(@NonNull final NetworkAgentInfo nai, final NetworkScore score) {
Chalard Jean8cdee3a2020-03-04 17:45:08 +09009749 if (VDBG || DDBG) log("updateNetworkScore for " + nai.toShortString() + " to " + score);
9750 nai.setScore(score);
Chalard Jeanb0b3bc62019-11-07 18:54:49 +09009751 rematchAllNetworksAndRequests();
Robert Greenwalt06c734e2014-05-27 13:20:24 -07009752 }
9753
Erik Kline99f301b2017-02-15 19:59:17 +09009754 // Notify only this one new request of the current state. Transfer all the
9755 // current state by calling NetworkCapabilities and LinkProperties callbacks
9756 // so that callers can be guaranteed to have as close to atomicity in state
9757 // transfer as can be supported by this current API.
9758 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen5eba9d72016-10-27 15:05:50 -07009759 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Kline99f301b2017-02-15 19:59:17 +09009760 if (nri.mPendingIntent != null) {
9761 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
9762 // Attempt no subsequent state pushes where intents are involved.
9763 return;
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009764 }
Erik Kline99f301b2017-02-15 19:59:17 +09009765
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009766 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
junyulaif2c67e42018-08-07 19:50:45 +08009767 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009768 final boolean vpnBlocked = isUidBlockedByVpn(nri.mAsUid, mVpnBlockedUidRanges);
9769 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE,
9770 getBlockedState(blockedReasons, metered, vpnBlocked));
junyulaif2c67e42018-08-07 19:50:45 +08009771 }
9772
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009773 // Notify the requests on this NAI that the network is now lingered.
9774 private void notifyNetworkLosing(@NonNull final NetworkAgentInfo nai, final long now) {
junyulai2b6f0c22021-02-03 20:15:30 +08009775 final int lingerTime = (int) (nai.getInactivityExpiry() - now);
Chalard Jean8fd82ae2019-12-04 18:49:18 +09009776 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
9777 }
9778
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009779 private static int getBlockedState(int reasons, boolean metered, boolean vpnBlocked) {
9780 if (!metered) reasons &= ~BLOCKED_METERED_REASON_MASK;
9781 return vpnBlocked
9782 ? reasons | BLOCKED_REASON_LOCKDOWN_VPN
9783 : reasons & ~BLOCKED_REASON_LOCKDOWN_VPN;
9784 }
9785
9786 private void setUidBlockedReasons(int uid, @BlockedReason int blockedReasons) {
9787 if (blockedReasons == BLOCKED_REASON_NONE) {
9788 mUidBlockedReasons.delete(uid);
9789 } else {
9790 mUidBlockedReasons.put(uid, blockedReasons);
9791 }
9792 }
9793
junyulaif2c67e42018-08-07 19:50:45 +08009794 /**
9795 * Notify of the blocked state apps with a registered callback matching a given NAI.
9796 *
9797 * Unlike other callbacks, blocked status is different between each individual uid. So for
9798 * any given nai, all requests need to be considered according to the uid who filed it.
9799 *
9800 * @param nai The target NetworkAgentInfo.
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009801 * @param oldMetered True if the previous network capabilities were metered.
9802 * @param newMetered True if the current network capabilities are metered.
9803 * @param oldBlockedUidRanges list of UID ranges previously blocked by lockdown VPN.
9804 * @param newBlockedUidRanges list of UID ranges blocked by lockdown VPN.
junyulaif2c67e42018-08-07 19:50:45 +08009805 */
9806 private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
Sudheer Shanka9967d462021-03-18 19:09:25 +00009807 boolean newMetered, List<UidRange> oldBlockedUidRanges,
9808 List<UidRange> newBlockedUidRanges) {
junyulaif2c67e42018-08-07 19:50:45 +08009809
9810 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9811 NetworkRequest nr = nai.requestAt(i);
9812 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009813
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009814 final int blockedReasons = mUidBlockedReasons.get(nri.mAsUid, BLOCKED_REASON_NONE);
9815 final boolean oldVpnBlocked = isUidBlockedByVpn(nri.mAsUid, oldBlockedUidRanges);
9816 final boolean newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009817 ? isUidBlockedByVpn(nri.mAsUid, newBlockedUidRanges)
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009818 : oldVpnBlocked;
9819
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009820 final int oldBlockedState = getBlockedState(blockedReasons, oldMetered, oldVpnBlocked);
9821 final int newBlockedState = getBlockedState(blockedReasons, newMetered, newVpnBlocked);
9822 if (oldBlockedState != newBlockedState) {
junyulaif2c67e42018-08-07 19:50:45 +08009823 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009824 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009825 }
9826 }
9827 }
9828
9829 /**
Sudheer Shanka9967d462021-03-18 19:09:25 +00009830 * Notify apps with a given UID of the new blocked state according to new uid state.
junyulaif2c67e42018-08-07 19:50:45 +08009831 * @param uid The uid for which the rules changed.
Sudheer Shanka9967d462021-03-18 19:09:25 +00009832 * @param blockedReasons The reasons for why an uid is blocked.
junyulaif2c67e42018-08-07 19:50:45 +08009833 */
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009834 private void maybeNotifyNetworkBlockedForNewState(int uid, @BlockedReason int blockedReasons) {
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009835 for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
junyulaif2c67e42018-08-07 19:50:45 +08009836 final boolean metered = nai.networkCapabilities.isMetered();
Lorenzo Colitti3f54f102020-12-12 00:51:11 +09009837 final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
Sudheer Shanka9967d462021-03-18 19:09:25 +00009838
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009839 final int oldBlockedState = getBlockedState(
9840 mUidBlockedReasons.get(uid, BLOCKED_REASON_NONE), metered, vpnBlocked);
9841 final int newBlockedState = getBlockedState(blockedReasons, metered, vpnBlocked);
9842 if (oldBlockedState == newBlockedState) {
junyulai7509e6e2019-04-08 16:58:22 +08009843 continue;
junyulaif2c67e42018-08-07 19:50:45 +08009844 }
junyulaif2c67e42018-08-07 19:50:45 +08009845 for (int i = 0; i < nai.numNetworkRequests(); i++) {
9846 NetworkRequest nr = nai.requestAt(i);
9847 NetworkRequestInfo nri = mNetworkRequests.get(nr);
Lorenzo Colitti3e367f42021-03-12 22:50:57 +09009848 if (nri != null && nri.mAsUid == uid) {
Lorenzo Colitti79c6f222021-03-18 00:54:57 +09009849 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
9850 newBlockedState);
junyulaif2c67e42018-08-07 19:50:45 +08009851 }
9852 }
9853 }
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009854 }
9855
Chalard Jean3a3f5f22019-04-10 23:07:55 +09009856 @VisibleForTesting
9857 protected void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colitticfb36572014-07-31 23:20:17 +09009858 // The NetworkInfo we actually send out has no bearing on the real
9859 // state of affairs. For example, if the default connection is mobile,
9860 // and a request for HIPRI has just gone away, we need to pretend that
9861 // HIPRI has just disconnected. So we need to set the type to HIPRI and
9862 // the state to DISCONNECTED, even though the network is of type MOBILE
9863 // and is still connected.
9864 NetworkInfo info = new NetworkInfo(nai.networkInfo);
9865 info.setType(type);
Lorenzo Colittie30db8d2021-03-10 00:18:59 +09009866 filterForLegacyLockdown(info);
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009867 if (state != DetailedState.DISCONNECTED) {
9868 info.setDetailedState(state, null, info.getExtraInfo());
Erik Klineb8836592014-12-08 16:25:20 +09009869 sendConnectedBroadcast(info);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009870 } else {
Robert Greenwalt7fb8adc2015-06-24 13:23:42 -07009871 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt802c1102014-06-02 15:32:02 -07009872 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
9873 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
9874 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
9875 if (info.isFailover()) {
9876 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
9877 nai.networkInfo.setFailover(false);
9878 }
9879 if (info.getReason() != null) {
9880 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
9881 }
9882 if (info.getExtraInfo() != null) {
9883 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
9884 }
9885 NetworkAgentInfo newDefaultAgent = null;
Chalard Jean5b409c72021-02-04 13:12:59 +09009886 if (nai.isSatisfyingRequest(mDefaultRequest.mRequests.get(0).requestId)) {
James Mattis2516da32021-01-31 17:06:19 -08009887 newDefaultAgent = mDefaultRequest.getSatisfier();
Robert Greenwalt802c1102014-06-02 15:32:02 -07009888 if (newDefaultAgent != null) {
9889 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
9890 newDefaultAgent.networkInfo);
9891 } else {
9892 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
9893 }
9894 }
9895 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
9896 mDefaultInetConditionPublished);
Erik Klineb8836592014-12-08 16:25:20 +09009897 sendStickyBroadcast(intent);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009898 if (newDefaultAgent != null) {
Erik Klineb8836592014-12-08 16:25:20 +09009899 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt802c1102014-06-02 15:32:02 -07009900 }
9901 }
9902 }
9903
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009904 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
hiroaki.yokoyamaa1a397d2018-10-16 12:50:33 +09009905 if (VDBG || DDBG) {
Hugo Benichi8d962922017-03-22 17:07:57 +09009906 String notification = ConnectivityManager.getCallbackName(notifyType);
Chalard Jean49707572019-12-10 21:07:02 +09009907 log("notifyType " + notification + " for " + networkAgent.toShortString());
Hugo Benichi8d962922017-03-22 17:07:57 +09009908 }
Lorenzo Colitti99236d12016-07-01 01:37:11 +09009909 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
9910 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwaltf99b8392014-03-26 16:47:06 -07009911 NetworkRequestInfo nri = mNetworkRequests.get(nr);
9912 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009913 if (nri.mPendingIntent == null) {
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009914 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin60d379b2014-11-05 10:32:09 -08009915 } else {
9916 sendPendingIntentForRequest(nri, networkAgent, notifyType);
9917 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009918 }
Robert Greenwalte20f7a22014-04-18 15:25:25 -07009919 }
Robert Greenwaltbe46b752014-05-13 21:41:06 -07009920
Lorenzo Colitti79869ea2016-07-01 01:53:25 +09009921 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
9922 notifyNetworkCallbacks(networkAgent, notifyType, 0);
9923 }
9924
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009925 /**
Lorenzo Colitti24861882018-01-19 00:50:48 +09009926 * Returns the list of all interfaces that could be used by network traffic that does not
9927 * explicitly specify a network. This includes the default network, but also all VPNs that are
9928 * currently connected.
9929 *
9930 * Must be called on the handler thread.
9931 */
junyulaie7c7d2a2021-01-26 15:29:15 +08009932 @NonNull
9933 private ArrayList<Network> getDefaultNetworks() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009934 ensureRunningOnConnectivityServiceThread();
James Mattise3ef1912020-12-20 11:09:58 -08009935 final ArrayList<Network> defaultNetworks = new ArrayList<>();
James Mattis2516da32021-01-31 17:06:19 -08009936 final Set<Integer> activeNetIds = new ArraySet<>();
9937 for (final NetworkRequestInfo nri : mDefaultNetworkRequests) {
9938 if (nri.isBeingSatisfied()) {
9939 activeNetIds.add(nri.getSatisfier().network().netId);
9940 }
9941 }
Remi NGUYEN VAN77b0c1c2020-12-23 12:45:08 +09009942 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
Lorenzo Colitti275ee602022-08-09 19:29:12 +09009943 if (activeNetIds.contains(nai.network().netId) || nai.isVPN()) {
Lorenzo Colitti24861882018-01-19 00:50:48 +09009944 defaultNetworks.add(nai.network);
9945 }
9946 }
junyulaie7c7d2a2021-01-26 15:29:15 +08009947 return defaultNetworks;
Lorenzo Colitti24861882018-01-19 00:50:48 +09009948 }
9949
9950 /**
Lorenzo Colittic7563342019-06-24 13:50:45 +09009951 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
9952 * active iface's tracked properties has changed.
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009953 */
Jeff Davidsonf73c15c2016-01-20 11:35:38 -08009954 private void notifyIfacesChangedForNetworkStats() {
Varun Anandf3fd8dd2019-02-07 14:13:13 -08009955 ensureRunningOnConnectivityServiceThread();
9956 String activeIface = null;
9957 LinkProperties activeLinkProperties = getActiveLinkProperties();
9958 if (activeLinkProperties != null) {
9959 activeIface = activeLinkProperties.getInterfaceName();
9960 }
Benedict Wong9308cd32019-06-12 17:46:31 +00009961
junyulai2050bed2021-01-23 09:46:34 +08009962 final UnderlyingNetworkInfo[] underlyingNetworkInfos = getAllVpnInfo();
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009963 try {
junyulaide41fc22021-01-22 22:46:01 +08009964 final ArrayList<NetworkStateSnapshot> snapshots = new ArrayList<>();
Chalard Jean46bfbf02022-02-02 00:56:25 +09009965 snapshots.addAll(getAllNetworkStateSnapshots());
junyulaie7c7d2a2021-01-26 15:29:15 +08009966 mStatsManager.notifyNetworkStatus(getDefaultNetworks(),
9967 snapshots, activeIface, Arrays.asList(underlyingNetworkInfos));
Jeff Sharkeyaa6ff6c2014-12-08 14:50:12 -08009968 } catch (Exception ignored) {
9969 }
9970 }
9971
Sreeram Ramachandrane4586322014-07-27 14:18:26 -07009972 @Override
Udam Sainicd645462016-01-04 12:16:14 -08009973 public String getCaptivePortalServerUrl() {
paulhu8e96a752019-08-12 16:25:11 +08009974 enforceNetworkStackOrSettingsPermission();
Remi NGUYEN VAN21c854a2021-03-08 22:05:03 +09009975 String settingUrl = mResources.get().getString(
Remi NGUYEN VAN97fad722021-03-19 17:41:48 +09009976 R.string.config_networkCaptivePortalServerUrl);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009977
9978 if (!TextUtils.isEmpty(settingUrl)) {
9979 return settingUrl;
9980 }
9981
9982 settingUrl = Settings.Global.getString(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +08009983 ConnectivitySettingsManager.CAPTIVE_PORTAL_HTTP_URL);
Niklas Lindgrenfd6f92e2018-12-07 11:08:04 +01009984 if (!TextUtils.isEmpty(settingUrl)) {
9985 return settingUrl;
9986 }
9987
9988 return DEFAULT_CAPTIVE_PORTAL_HTTP_URL;
Udam Sainicd645462016-01-04 12:16:14 -08009989 }
9990
9991 @Override
junyulai070f9ff2019-01-16 20:23:34 +08009992 public void startNattKeepalive(Network network, int intervalSeconds,
9993 ISocketKeepaliveCallback cb, String srcAddr, int srcPort, String dstAddr) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +09009994 enforceKeepalivePermission();
9995 mKeepaliveTracker.startNattKeepalive(
junyulai7e06ad42019-03-04 22:45:36 +08009996 getNetworkAgentInfoForNetwork(network), null /* fd */,
chiachangwang9ef4ffe2023-01-18 01:19:27 +00009997 intervalSeconds, cb, srcAddr, srcPort, dstAddr, NattSocketKeepalive.NATT_PORT,
9998 // Keep behavior of the deprecated method as it is. Set automaticOnOffKeepalives to
chiachangwang676c84e2023-02-14 09:22:05 +00009999 // false and set the underpinned network to null because there is no way and no
10000 // plan to configure automaticOnOffKeepalives or underpinnedNetwork in this
10001 // deprecated method.
10002 false /* automaticOnOffKeepalives */, null /* underpinnedNetwork */);
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010003 }
10004
10005 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010006 public void startNattKeepaliveWithFd(Network network, ParcelFileDescriptor pfd, int resourceId,
junyulai070f9ff2019-01-16 20:23:34 +080010007 int intervalSeconds, ISocketKeepaliveCallback cb, String srcAddr,
chiachangwang676c84e2023-02-14 09:22:05 +000010008 String dstAddr, boolean automaticOnOffKeepalives, Network underpinnedNetwork) {
Josh Gao461a1222020-06-16 15:58:11 -070010009 try {
Chiachang Wang04a34b62021-01-19 15:35:03 +080010010 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010011 mKeepaliveTracker.startNattKeepalive(
10012 getNetworkAgentInfoForNetwork(network), fd, resourceId,
chiachangwang676c84e2023-02-14 09:22:05 +000010013 intervalSeconds, cb, srcAddr, dstAddr, NattSocketKeepalive.NATT_PORT,
10014 automaticOnOffKeepalives, underpinnedNetwork);
Josh Gao461a1222020-06-16 15:58:11 -070010015 } finally {
10016 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10017 // startNattKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010018 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10019 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010020 }
10021 }
junyulaid05a1922019-01-15 11:32:44 +080010022 }
10023
10024 @Override
Chiachang Wang04a34b62021-01-19 15:35:03 +080010025 public void startTcpKeepalive(Network network, ParcelFileDescriptor pfd, int intervalSeconds,
junyulai070f9ff2019-01-16 20:23:34 +080010026 ISocketKeepaliveCallback cb) {
Josh Gao461a1222020-06-16 15:58:11 -070010027 try {
10028 enforceKeepalivePermission();
Chiachang Wang04a34b62021-01-19 15:35:03 +080010029 final FileDescriptor fd = pfd.getFileDescriptor();
Josh Gao461a1222020-06-16 15:58:11 -070010030 mKeepaliveTracker.startTcpKeepalive(
10031 getNetworkAgentInfoForNetwork(network), fd, intervalSeconds, cb);
10032 } finally {
10033 // FileDescriptors coming from AIDL calls must be manually closed to prevent leaks.
10034 // startTcpKeepalive calls Os.dup(fd) before returning, so we can close immediately.
Chiachang Wang04a34b62021-01-19 15:35:03 +080010035 if (pfd != null && Binder.getCallingPid() != Process.myPid()) {
10036 IoUtils.closeQuietly(pfd);
Josh Gao461a1222020-06-16 15:58:11 -070010037 }
10038 }
junyulai0835a1e2019-01-08 20:04:33 +080010039 }
10040
10041 @Override
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010042 public void stopKeepalive(@NonNull final ISocketKeepaliveCallback cb) {
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010043 mHandler.sendMessage(mHandler.obtainMessage(
Chalard Jeanf0b261e2023-02-03 22:11:20 +090010044 NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE, 0, SocketKeepalive.SUCCESS,
10045 Objects.requireNonNull(cb).asBinder()));
Lorenzo Colitti0b798a82015-06-15 14:29:22 +090010046 }
10047
10048 @Override
Stuart Scottd5463642015-04-02 18:00:02 -070010049 public void factoryReset() {
paulhu8e96a752019-08-12 16:25:11 +080010050 enforceSettingsPermission();
Stuart Scottd198fe12015-04-20 14:07:45 -070010051
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010052 final int uid = mDeps.getCallingUid();
lucaslin75ff7022020-12-17 04:14:35 +080010053 final long token = Binder.clearCallingIdentity();
10054 try {
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010055 if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_NETWORK_RESET,
10056 UserHandle.getUserHandleForUid(uid))) {
10057 return;
10058 }
10059
Heemin Seogdb8489d2019-06-12 09:21:44 -070010060 final IpMemoryStore ipMemoryStore = IpMemoryStore.getMemoryStore(mContext);
10061 ipMemoryStore.factoryReset();
Chiachang Wangfe28d9b2021-05-19 10:13:22 +080010062
10063 // Turn airplane mode off
10064 setAirplaneMode(false);
10065
10066 // restore private DNS settings to default mode (opportunistic)
10067 if (!mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
10068 UserHandle.getUserHandleForUid(uid))) {
10069 ConnectivitySettingsManager.setPrivateDnsMode(mContext,
10070 PRIVATE_DNS_MODE_OPPORTUNISTIC);
10071 }
10072
10073 Settings.Global.putString(mContext.getContentResolver(),
10074 ConnectivitySettingsManager.NETWORK_AVOID_BAD_WIFI, null);
lucaslin75ff7022020-12-17 04:14:35 +080010075 } finally {
10076 Binder.restoreCallingIdentity(token);
10077 }
Stuart Scottd5463642015-04-02 18:00:02 -070010078 }
Paul Jensen6eb94e62015-07-01 14:16:32 -040010079
Ricky Wai7097cc92018-01-23 04:09:45 +000010080 @Override
10081 public byte[] getNetworkWatchlistConfigHash() {
10082 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
10083 if (nwm == null) {
10084 loge("Unable to get NetworkWatchlistManager");
10085 return null;
10086 }
10087 // Redirect it to network watchlist service to access watchlist file and calculate hash.
10088 return nwm.getWatchlistConfigHash();
10089 }
10090
Hugo Benichibe0c7652016-05-31 16:28:06 +090010091 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichi2efffd72017-11-11 08:06:43 +090010092 int[] transports = nai.networkCapabilities.getTransportTypes();
Serik Beketayevec8ad212020-12-07 22:43:07 -080010093 mMetricsLog.log(nai.network.getNetId(), transports, new NetworkEvent(evtype));
Erik Klineabdd3f82016-04-14 17:30:59 +090010094 }
Hugo Benichif4210292017-04-21 15:07:12 +090010095
10096 private static boolean toBool(int encodedBoolean) {
10097 return encodedBoolean != 0; // Only 0 means false.
10098 }
10099
10100 private static int encodeBool(boolean b) {
10101 return b ? 1 : 0;
10102 }
mswest4632928412018-03-12 10:34:34 -070010103
10104 @Override
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010105 public int handleShellCommand(@NonNull ParcelFileDescriptor in,
10106 @NonNull ParcelFileDescriptor out, @NonNull ParcelFileDescriptor err,
10107 @NonNull String[] args) {
10108 return new ShellCmd().exec(this, in.getFileDescriptor(), out.getFileDescriptor(),
10109 err.getFileDescriptor(), args);
mswest4632928412018-03-12 10:34:34 -070010110 }
10111
Chiachang Wang77ae8a02020-10-12 15:20:07 +080010112 private class ShellCmd extends BasicShellCommandHandler {
mswest4632928412018-03-12 10:34:34 -070010113 @Override
10114 public int onCommand(String cmd) {
10115 if (cmd == null) {
10116 return handleDefaultCommands(cmd);
10117 }
10118 final PrintWriter pw = getOutPrintWriter();
10119 try {
10120 switch (cmd) {
10121 case "airplane-mode":
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010122 // Usage : adb shell cmd connectivity airplane-mode [enable|disable]
10123 // If no argument, get and display the current status
mswest4632928412018-03-12 10:34:34 -070010124 final String action = getNextArg();
10125 if ("enable".equals(action)) {
10126 setAirplaneMode(true);
10127 return 0;
10128 } else if ("disable".equals(action)) {
10129 setAirplaneMode(false);
10130 return 0;
10131 } else if (action == null) {
10132 final ContentResolver cr = mContext.getContentResolver();
10133 final int enabled = Settings.Global.getInt(cr,
10134 Settings.Global.AIRPLANE_MODE_ON);
10135 pw.println(enabled == 0 ? "disabled" : "enabled");
10136 return 0;
10137 } else {
10138 onHelp();
10139 return -1;
10140 }
Chalard Jean7a1d7a82021-08-05 21:02:22 +090010141 case "reevaluate":
10142 // Usage : adb shell cmd connectivity reevaluate <netId>
10143 // If netId is omitted, then reevaluate the default network
10144 final String netId = getNextArg();
10145 final NetworkAgentInfo nai;
10146 if (null == netId) {
10147 // Note that the command is running on the wrong thread to call this,
10148 // so this could in principle return stale data. But it can't crash.
10149 nai = getDefaultNetwork();
10150 } else {
10151 // If netId can't be parsed, this throws NumberFormatException, which
10152 // is passed back to adb who prints it.
10153 nai = getNetworkAgentInfoForNetId(Integer.parseInt(netId));
10154 }
10155 if (null == nai) {
10156 pw.println("Unknown network (net ID not found or no default network)");
10157 return 0;
10158 }
10159 Log.d(TAG, "Reevaluating network " + nai.network);
10160 reportNetworkConnectivity(nai.network, !nai.isValidated());
10161 return 0;
mswest4632928412018-03-12 10:34:34 -070010162 default:
10163 return handleDefaultCommands(cmd);
10164 }
10165 } catch (Exception e) {
10166 pw.println(e);
10167 }
10168 return -1;
10169 }
10170
10171 @Override
10172 public void onHelp() {
10173 PrintWriter pw = getOutPrintWriter();
10174 pw.println("Connectivity service commands:");
10175 pw.println(" help");
10176 pw.println(" Print this help text.");
10177 pw.println(" airplane-mode [enable|disable]");
10178 pw.println(" Turn airplane mode on or off.");
10179 pw.println(" airplane-mode");
10180 pw.println(" Get airplane mode.");
10181 }
10182 }
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010183
Remi NGUYEN VAN06830742021-03-06 00:11:24 +090010184 private int getVpnType(@Nullable NetworkAgentInfo vpn) {
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010185 if (vpn == null) return VpnManager.TYPE_VPN_NONE;
10186 final TransportInfo ti = vpn.networkCapabilities.getTransportInfo();
10187 if (!(ti instanceof VpnTransportInfo)) return VpnManager.TYPE_VPN_NONE;
Chiachang Wang6ec9b8d2021-04-20 15:41:24 +080010188 return ((VpnTransportInfo) ti).getType();
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010189 }
10190
Lorenzo Colitti580d0d52022-10-13 19:56:58 +090010191 private void maybeUpdateWifiRoamTimestamp(@NonNull NetworkAgentInfo nai,
10192 @NonNull NetworkCapabilities nc) {
he_won.hwang881307a2022-03-15 21:23:52 +090010193 final TransportInfo prevInfo = nai.networkCapabilities.getTransportInfo();
10194 final TransportInfo newInfo = nc.getTransportInfo();
10195 if (!(prevInfo instanceof WifiInfo) || !(newInfo instanceof WifiInfo)) {
10196 return;
10197 }
10198 if (!TextUtils.equals(((WifiInfo)prevInfo).getBSSID(), ((WifiInfo)newInfo).getBSSID())) {
Chalard Jean254bd162022-08-25 13:04:51 +090010199 nai.lastRoamTime = SystemClock.elapsedRealtime();
he_won.hwang881307a2022-03-15 21:23:52 +090010200 }
10201 }
10202
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010203 /**
10204 * @param connectionInfo the connection to resolve.
10205 * @return {@code uid} if the connection is found and the app has permission to observe it
10206 * (e.g., if it is associated with the calling VPN app's tunnel) or {@code INVALID_UID} if the
10207 * connection is not found.
10208 */
10209 public int getConnectionOwnerUid(ConnectionInfo connectionInfo) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010210 if (connectionInfo.protocol != IPPROTO_TCP && connectionInfo.protocol != IPPROTO_UDP) {
10211 throw new IllegalArgumentException("Unsupported protocol " + connectionInfo.protocol);
10212 }
10213
Lorenzo Colitti3be9df12021-02-04 01:47:38 +090010214 final int uid = mDeps.getConnectionOwnerUid(connectionInfo.protocol,
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010215 connectionInfo.local, connectionInfo.remote);
10216
Lorenzo Colittia5a903d2021-02-04 00:18:27 +090010217 if (uid == INVALID_UID) return uid; // Not found.
10218
10219 // Connection owner UIDs are visible only to the network stack and to the VpnService-based
10220 // VPN, if any, that applies to the UID that owns the connection.
10221 if (checkNetworkStackPermission()) return uid;
10222
10223 final NetworkAgentInfo vpn = getVpnForUid(uid);
10224 if (vpn == null || getVpnType(vpn) != VpnManager.TYPE_VPN_SERVICE
Lorenzo Colitti9bff86e2021-03-12 22:39:08 +090010225 || vpn.networkCapabilities.getOwnerUid() != mDeps.getCallingUid()) {
Jeff Vander Stoep39a51e02018-07-23 10:57:53 -070010226 return INVALID_UID;
10227 }
10228
10229 return uid;
10230 }
Pavel Grafove87b7ce2018-12-14 13:51:07 +000010231
Benedict Wong493e04b2018-11-09 14:45:34 -080010232 /**
10233 * Returns a IBinder to a TestNetworkService. Will be lazily created as needed.
10234 *
10235 * <p>The TestNetworkService must be run in the system server due to TUN creation.
10236 */
10237 @Override
10238 public IBinder startOrGetTestNetworkService() {
10239 synchronized (mTNSLock) {
10240 TestNetworkService.enforceTestNetworkPermissions(mContext);
10241
10242 if (mTNS == null) {
lucaslin23efc582021-02-24 13:49:42 +080010243 mTNS = new TestNetworkService(mContext);
Benedict Wong493e04b2018-11-09 14:45:34 -080010244 }
10245
10246 return mTNS;
10247 }
10248 }
Cody Kestingd199a9d2019-12-17 12:55:28 -080010249
Cody Kesting73708bf2019-12-18 10:57:50 -080010250 /**
10251 * Handler used for managing all Connectivity Diagnostics related functions.
10252 *
10253 * @see android.net.ConnectivityDiagnosticsManager
10254 *
10255 * TODO(b/147816404): Explore moving ConnectivityDiagnosticsHandler to a separate file
10256 */
10257 @VisibleForTesting
10258 class ConnectivityDiagnosticsHandler extends Handler {
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010259 private final String mTag = ConnectivityDiagnosticsHandler.class.getSimpleName();
10260
Cody Kesting73708bf2019-12-18 10:57:50 -080010261 /**
10262 * Used to handle ConnectivityDiagnosticsCallback registration events from {@link
10263 * android.net.ConnectivityDiagnosticsManager}.
10264 * obj = ConnectivityDiagnosticsCallbackInfo with IConnectivityDiagnosticsCallback and
10265 * NetworkRequestInfo to be registered
10266 */
10267 private static final int EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 1;
10268
10269 /**
10270 * Used to handle ConnectivityDiagnosticsCallback unregister events from {@link
10271 * android.net.ConnectivityDiagnosticsManager}.
10272 * obj = the IConnectivityDiagnosticsCallback to be unregistered
10273 * arg1 = the uid of the caller
10274 */
10275 private static final int EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK = 2;
10276
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010277 /**
10278 * Event for {@link NetworkStateTrackerHandler} to trigger ConnectivityReport callbacks
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010279 * after processing {@link #CMD_SEND_CONNECTIVITY_REPORT} events.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010280 * obj = {@link ConnectivityReportEvent} representing ConnectivityReport info reported from
10281 * NetworkMonitor.
10282 * data = PersistableBundle of extras passed from NetworkMonitor.
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010283 */
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010284 private static final int CMD_SEND_CONNECTIVITY_REPORT = 3;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010285
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010286 /**
10287 * Event for NetworkMonitor to inform ConnectivityService that a potential data stall has
10288 * been detected on the network.
10289 * obj = Long the timestamp (in millis) for when the suspected data stall was detected.
10290 * arg1 = {@link DataStallReport#DetectionMethod} indicating the detection method.
10291 * arg2 = NetID.
10292 * data = PersistableBundle of extras passed from NetworkMonitor.
10293 */
10294 private static final int EVENT_DATA_STALL_SUSPECTED = 4;
10295
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010296 /**
10297 * Event for ConnectivityDiagnosticsHandler to handle network connectivity being reported to
10298 * the platform. This event will invoke {@link
10299 * IConnectivityDiagnosticsCallback#onNetworkConnectivityReported} for permissioned
10300 * callbacks.
Cody Kestingf1120be2020-08-03 18:01:40 -070010301 * obj = ReportedNetworkConnectivityInfo with info on reported Network connectivity.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010302 */
10303 private static final int EVENT_NETWORK_CONNECTIVITY_REPORTED = 5;
10304
Cody Kesting73708bf2019-12-18 10:57:50 -080010305 private ConnectivityDiagnosticsHandler(Looper looper) {
10306 super(looper);
10307 }
10308
10309 @Override
10310 public void handleMessage(Message msg) {
10311 switch (msg.what) {
10312 case EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10313 handleRegisterConnectivityDiagnosticsCallback(
10314 (ConnectivityDiagnosticsCallbackInfo) msg.obj);
10315 break;
10316 }
10317 case EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK: {
10318 handleUnregisterConnectivityDiagnosticsCallback(
10319 (IConnectivityDiagnosticsCallback) msg.obj, msg.arg1);
10320 break;
10321 }
Lorenzo Colitti0261ced2022-02-18 00:23:56 +090010322 case CMD_SEND_CONNECTIVITY_REPORT: {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010323 final ConnectivityReportEvent reportEvent =
10324 (ConnectivityReportEvent) msg.obj;
10325
Aaron Huang959d3642021-01-21 15:47:41 +080010326 handleNetworkTestedWithExtras(reportEvent, reportEvent.mExtras);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010327 break;
10328 }
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010329 case EVENT_DATA_STALL_SUSPECTED: {
10330 final NetworkAgentInfo nai = getNetworkAgentInfoForNetId(msg.arg2);
Aaron Huang959d3642021-01-21 15:47:41 +080010331 final Pair<Long, PersistableBundle> arg =
10332 (Pair<Long, PersistableBundle>) msg.obj;
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010333 if (nai == null) break;
10334
Aaron Huang959d3642021-01-21 15:47:41 +080010335 handleDataStallSuspected(nai, arg.first, msg.arg1, arg.second);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010336 break;
10337 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010338 case EVENT_NETWORK_CONNECTIVITY_REPORTED: {
Cody Kestingf1120be2020-08-03 18:01:40 -070010339 handleNetworkConnectivityReported((ReportedNetworkConnectivityInfo) msg.obj);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010340 break;
10341 }
10342 default: {
10343 Log.e(mTag, "Unrecognized event in ConnectivityDiagnostics: " + msg.what);
10344 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010345 }
10346 }
10347 }
10348
10349 /** Class used for cleaning up IConnectivityDiagnosticsCallback instances after their death. */
10350 @VisibleForTesting
10351 class ConnectivityDiagnosticsCallbackInfo implements Binder.DeathRecipient {
10352 @NonNull private final IConnectivityDiagnosticsCallback mCb;
10353 @NonNull private final NetworkRequestInfo mRequestInfo;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010354 @NonNull private final String mCallingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010355
10356 @VisibleForTesting
10357 ConnectivityDiagnosticsCallbackInfo(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010358 @NonNull IConnectivityDiagnosticsCallback cb,
10359 @NonNull NetworkRequestInfo nri,
10360 @NonNull String callingPackageName) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010361 mCb = cb;
10362 mRequestInfo = nri;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010363 mCallingPackageName = callingPackageName;
Cody Kesting73708bf2019-12-18 10:57:50 -080010364 }
10365
10366 @Override
10367 public void binderDied() {
10368 log("ConnectivityDiagnosticsCallback IBinder died.");
10369 unregisterConnectivityDiagnosticsCallback(mCb);
10370 }
10371 }
10372
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010373 /**
10374 * Class used for sending information from {@link
10375 * NetworkMonitorCallbacks#notifyNetworkTestedWithExtras} to the handler for processing it.
10376 */
10377 private static class NetworkTestedResults {
10378 private final int mNetId;
10379 private final int mTestResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010380 @Nullable private final String mRedirectUrl;
10381
10382 private NetworkTestedResults(
10383 int netId, int testResult, long timestampMillis, @Nullable String redirectUrl) {
10384 mNetId = netId;
10385 mTestResult = testResult;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010386 mRedirectUrl = redirectUrl;
10387 }
10388 }
10389
10390 /**
10391 * Class used for sending information from {@link NetworkStateTrackerHandler} to {@link
10392 * ConnectivityDiagnosticsHandler}.
10393 */
10394 private static class ConnectivityReportEvent {
10395 private final long mTimestampMillis;
10396 @NonNull private final NetworkAgentInfo mNai;
Aaron Huang959d3642021-01-21 15:47:41 +080010397 private final PersistableBundle mExtras;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010398
Aaron Huang959d3642021-01-21 15:47:41 +080010399 private ConnectivityReportEvent(long timestampMillis, @NonNull NetworkAgentInfo nai,
10400 PersistableBundle p) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010401 mTimestampMillis = timestampMillis;
10402 mNai = nai;
Aaron Huang959d3642021-01-21 15:47:41 +080010403 mExtras = p;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010404 }
10405 }
10406
Cody Kestingf1120be2020-08-03 18:01:40 -070010407 /**
10408 * Class used for sending info for a call to {@link #reportNetworkConnectivity()} to {@link
10409 * ConnectivityDiagnosticsHandler}.
10410 */
10411 private static class ReportedNetworkConnectivityInfo {
10412 public final boolean hasConnectivity;
10413 public final boolean isNetworkRevalidating;
10414 public final int reporterUid;
10415 @NonNull public final NetworkAgentInfo nai;
10416
10417 private ReportedNetworkConnectivityInfo(
10418 boolean hasConnectivity,
10419 boolean isNetworkRevalidating,
10420 int reporterUid,
10421 @NonNull NetworkAgentInfo nai) {
10422 this.hasConnectivity = hasConnectivity;
10423 this.isNetworkRevalidating = isNetworkRevalidating;
10424 this.reporterUid = reporterUid;
10425 this.nai = nai;
10426 }
10427 }
10428
Cody Kesting73708bf2019-12-18 10:57:50 -080010429 private void handleRegisterConnectivityDiagnosticsCallback(
10430 @NonNull ConnectivityDiagnosticsCallbackInfo cbInfo) {
10431 ensureRunningOnConnectivityServiceThread();
10432
10433 final IConnectivityDiagnosticsCallback cb = cbInfo.mCb;
Cody Kesting31f1ff62020-03-05 10:46:02 -080010434 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010435 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
10436
James Mattis64b8b0f2020-11-24 17:40:49 -080010437 // Connectivity Diagnostics are meant to be used with a single network request. It would be
10438 // confusing for these networks to change when an NRI is satisfied in another layer.
10439 if (nri.isMultilayerRequest()) {
10440 throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
10441 + "network requests.");
10442 }
10443
Cody Kesting73708bf2019-12-18 10:57:50 -080010444 // This means that the client registered the same callback multiple times. Do
10445 // not override the previous entry, and exit silently.
Cody Kesting31f1ff62020-03-05 10:46:02 -080010446 if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010447 if (VDBG) log("Diagnostics callback is already registered");
10448
10449 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10450 // incremented when the NetworkRequestInfo is created as part of
10451 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010452 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting73708bf2019-12-18 10:57:50 -080010453 return;
10454 }
10455
Cody Kesting31f1ff62020-03-05 10:46:02 -080010456 mConnectivityDiagnosticsCallbacks.put(iCb, cbInfo);
Cody Kesting73708bf2019-12-18 10:57:50 -080010457
10458 try {
Cody Kesting31f1ff62020-03-05 10:46:02 -080010459 iCb.linkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010460 } catch (RemoteException e) {
10461 cbInfo.binderDied();
Cody Kestingb77bf702020-02-12 14:50:58 -080010462 return;
10463 }
10464
10465 // Once registered, provide ConnectivityReports for matching Networks
10466 final List<NetworkAgentInfo> matchingNetworks = new ArrayList<>();
10467 synchronized (mNetworkForNetId) {
10468 for (int i = 0; i < mNetworkForNetId.size(); i++) {
10469 final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
James Mattis64b8b0f2020-11-24 17:40:49 -080010470 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
10471 if (nai.satisfies(nri.mRequests.get(0))) {
Cody Kestingb77bf702020-02-12 14:50:58 -080010472 matchingNetworks.add(nai);
10473 }
10474 }
10475 }
10476 for (final NetworkAgentInfo nai : matchingNetworks) {
10477 final ConnectivityReport report = nai.getConnectivityReport();
10478 if (report == null) {
10479 continue;
10480 }
10481 if (!checkConnectivityDiagnosticsPermissions(
10482 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10483 continue;
10484 }
10485
10486 try {
10487 cb.onConnectivityReportAvailable(report);
10488 } catch (RemoteException e) {
10489 // Exception while sending the ConnectivityReport. Move on to the next network.
10490 }
Cody Kesting73708bf2019-12-18 10:57:50 -080010491 }
10492 }
10493
10494 private void handleUnregisterConnectivityDiagnosticsCallback(
10495 @NonNull IConnectivityDiagnosticsCallback cb, int uid) {
10496 ensureRunningOnConnectivityServiceThread();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010497 final IBinder iCb = cb.asBinder();
Cody Kesting73708bf2019-12-18 10:57:50 -080010498
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010499 final ConnectivityDiagnosticsCallbackInfo cbInfo =
10500 mConnectivityDiagnosticsCallbacks.remove(iCb);
10501 if (cbInfo == null) {
Cody Kesting73708bf2019-12-18 10:57:50 -080010502 if (VDBG) log("Removing diagnostics callback that is not currently registered");
10503 return;
10504 }
10505
Cody Kesting2b1a61c2020-03-30 12:43:49 -070010506 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kesting73708bf2019-12-18 10:57:50 -080010507
Cody Kesting70fa2b22020-12-02 12:16:56 -080010508 // Caller's UID must either be the registrants (if they are unregistering) or the System's
10509 // (if the Binder died)
10510 if (uid != nri.mUid && uid != Process.SYSTEM_UID) {
10511 if (DBG) loge("Uid(" + uid + ") not registrant's (" + nri.mUid + ") or System's");
Cody Kesting73708bf2019-12-18 10:57:50 -080010512 return;
10513 }
10514
Cody Kesting46cb1672020-03-04 13:35:20 -080010515 // Decrement the reference count for this NetworkRequestInfo. The reference count is
10516 // incremented when the NetworkRequestInfo is created as part of
10517 // enforceRequestCountLimit().
Junyu Lai00d92df2022-07-05 11:01:52 +080010518 nri.mPerUidCounter.decrementCount(nri.mUid);
Cody Kesting46cb1672020-03-04 13:35:20 -080010519
Cody Kesting31f1ff62020-03-05 10:46:02 -080010520 iCb.unlinkToDeath(cbInfo, 0);
Cody Kesting73708bf2019-12-18 10:57:50 -080010521 }
10522
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010523 private void handleNetworkTestedWithExtras(
10524 @NonNull ConnectivityReportEvent reportEvent, @NonNull PersistableBundle extras) {
10525 final NetworkAgentInfo nai = reportEvent.mNai;
Cody Kesting7febafb2020-02-11 10:03:26 -080010526 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010527 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010528 final ConnectivityReport report =
10529 new ConnectivityReport(
10530 reportEvent.mNai.network,
10531 reportEvent.mTimestampMillis,
10532 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010533 networkCapabilities,
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010534 extras);
Cody Kestingb77bf702020-02-12 14:50:58 -080010535 nai.setConnectivityReport(report);
Cody Kestingf1120be2020-08-03 18:01:40 -070010536
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010537 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010538 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010539 for (final IConnectivityDiagnosticsCallback cb : results) {
10540 try {
Cody Kestingfa1ef5e2020-03-05 15:19:48 -080010541 cb.onConnectivityReportAvailable(report);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010542 } catch (RemoteException ex) {
Cody Kestingf1120be2020-08-03 18:01:40 -070010543 loge("Error invoking onConnectivityReportAvailable", ex);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010544 }
10545 }
10546 }
10547
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010548 private void handleDataStallSuspected(
10549 @NonNull NetworkAgentInfo nai, long timestampMillis, int detectionMethod,
10550 @NonNull PersistableBundle extras) {
Cody Kesting7febafb2020-02-11 10:03:26 -080010551 final NetworkCapabilities networkCapabilities =
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010552 getNetworkCapabilitiesWithoutUids(nai.networkCapabilities);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010553 final DataStallReport report =
Cody Kestingf2852482020-02-04 21:52:09 -080010554 new DataStallReport(
10555 nai.network,
10556 timestampMillis,
10557 detectionMethod,
10558 nai.linkProperties,
Cody Kesting7febafb2020-02-11 10:03:26 -080010559 networkCapabilities,
Cody Kestingf2852482020-02-04 21:52:09 -080010560 extras);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010561 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010562 getMatchingPermissionedCallbacks(nai, Process.INVALID_UID);
Cody Kestingb12ad4c2020-01-06 16:55:35 -080010563 for (final IConnectivityDiagnosticsCallback cb : results) {
10564 try {
10565 cb.onDataStallSuspected(report);
10566 } catch (RemoteException ex) {
10567 loge("Error invoking onDataStallSuspected", ex);
10568 }
10569 }
10570 }
10571
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010572 private void handleNetworkConnectivityReported(
Cody Kestingf1120be2020-08-03 18:01:40 -070010573 @NonNull ReportedNetworkConnectivityInfo reportedNetworkConnectivityInfo) {
10574 final NetworkAgentInfo nai = reportedNetworkConnectivityInfo.nai;
10575 final ConnectivityReport cachedReport = nai.getConnectivityReport();
10576
10577 // If the Network is being re-validated as a result of this call to
10578 // reportNetworkConnectivity(), notify all permissioned callbacks. Otherwise, only notify
10579 // permissioned callbacks registered by the reporter.
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010580 final List<IConnectivityDiagnosticsCallback> results =
Cody Kestingf1120be2020-08-03 18:01:40 -070010581 getMatchingPermissionedCallbacks(
10582 nai,
10583 reportedNetworkConnectivityInfo.isNetworkRevalidating
10584 ? Process.INVALID_UID
10585 : reportedNetworkConnectivityInfo.reporterUid);
10586
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010587 for (final IConnectivityDiagnosticsCallback cb : results) {
10588 try {
Cody Kestingf1120be2020-08-03 18:01:40 -070010589 cb.onNetworkConnectivityReported(
10590 nai.network, reportedNetworkConnectivityInfo.hasConnectivity);
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010591 } catch (RemoteException ex) {
10592 loge("Error invoking onNetworkConnectivityReported", ex);
10593 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010594
10595 // If the Network isn't re-validating, also provide the cached report. If there is no
10596 // cached report, the Network is still being validated and a report will be sent once
10597 // validation is complete. Note that networks which never undergo validation will still
10598 // have a cached ConnectivityReport with RESULT_SKIPPED.
10599 if (!reportedNetworkConnectivityInfo.isNetworkRevalidating && cachedReport != null) {
10600 try {
10601 cb.onConnectivityReportAvailable(cachedReport);
10602 } catch (RemoteException ex) {
10603 loge("Error invoking onConnectivityReportAvailable", ex);
10604 }
10605 }
Cody Kesting5a9a2ae2020-01-07 11:18:54 -080010606 }
10607 }
10608
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010609 private NetworkCapabilities getNetworkCapabilitiesWithoutUids(@NonNull NetworkCapabilities nc) {
Lorenzo Colitti6424cf22021-05-10 00:49:14 +090010610 final NetworkCapabilities sanitized = new NetworkCapabilities(nc,
10611 NetworkCapabilities.REDACT_ALL);
Cody Kestingb1cd3eb2020-03-05 22:13:31 -080010612 sanitized.setUids(null);
10613 sanitized.setAdministratorUids(new int[0]);
10614 sanitized.setOwnerUid(Process.INVALID_UID);
10615 return sanitized;
Cody Kesting7febafb2020-02-11 10:03:26 -080010616 }
10617
Cody Kestingf1120be2020-08-03 18:01:40 -070010618 /**
10619 * Gets a list of ConnectivityDiagnostics callbacks that match the specified Network and uid.
10620 *
10621 * <p>If Process.INVALID_UID is specified, all matching callbacks will be returned.
10622 */
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010623 private List<IConnectivityDiagnosticsCallback> getMatchingPermissionedCallbacks(
Cody Kestingf1120be2020-08-03 18:01:40 -070010624 @NonNull NetworkAgentInfo nai, int uid) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010625 final List<IConnectivityDiagnosticsCallback> results = new ArrayList<>();
Cody Kesting31f1ff62020-03-05 10:46:02 -080010626 for (Entry<IBinder, ConnectivityDiagnosticsCallbackInfo> entry :
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010627 mConnectivityDiagnosticsCallbacks.entrySet()) {
10628 final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
10629 final NetworkRequestInfo nri = cbInfo.mRequestInfo;
Cody Kestingf1120be2020-08-03 18:01:40 -070010630
James Mattis64b8b0f2020-11-24 17:40:49 -080010631 // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
Cody Kestingf1120be2020-08-03 18:01:40 -070010632 if (!nai.satisfies(nri.mRequests.get(0))) {
10633 continue;
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010634 }
Cody Kestingf1120be2020-08-03 18:01:40 -070010635
10636 // UID for this callback must either be:
10637 // - INVALID_UID (which sends callbacks to all UIDs), or
10638 // - The callback's owner (the owner called reportNetworkConnectivity() and is being
10639 // notified as a result)
10640 if (uid != Process.INVALID_UID && uid != nri.mUid) {
10641 continue;
10642 }
10643
10644 if (!checkConnectivityDiagnosticsPermissions(
10645 nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
10646 continue;
10647 }
10648
10649 results.add(entry.getValue().mCb);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010650 }
10651 return results;
10652 }
10653
Cody Kesting7474f672021-05-11 14:22:40 -070010654 private boolean isLocationPermissionRequiredForConnectivityDiagnostics(
10655 @NonNull NetworkAgentInfo nai) {
10656 // TODO(b/188483916): replace with a transport-agnostic location-aware check
10657 return nai.networkCapabilities.hasTransport(TRANSPORT_WIFI);
10658 }
10659
Cody Kesting160ef392021-05-05 13:17:22 -070010660 private boolean hasLocationPermission(String packageName, int uid) {
10661 // LocationPermissionChecker#checkLocationPermission can throw SecurityException if the uid
10662 // and package name don't match. Throwing on the CS thread is not acceptable, so wrap the
10663 // call in a try-catch.
10664 try {
10665 if (!mLocationPermissionChecker.checkLocationPermission(
10666 packageName, null /* featureId */, uid, null /* message */)) {
10667 return false;
10668 }
10669 } catch (SecurityException e) {
10670 return false;
10671 }
10672
10673 return true;
10674 }
10675
10676 private boolean ownsVpnRunningOverNetwork(int uid, Network network) {
10677 for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
Lorenzo Colittibd079452021-07-02 11:47:57 +090010678 if (virtual.propagateUnderlyingCapabilities()
Cody Kesting160ef392021-05-05 13:17:22 -070010679 && virtual.networkCapabilities.getOwnerUid() == uid
10680 && CollectionUtils.contains(virtual.declaredUnderlyingNetworks, network)) {
10681 return true;
10682 }
10683 }
10684
10685 return false;
10686 }
10687
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010688 @VisibleForTesting
10689 boolean checkConnectivityDiagnosticsPermissions(
10690 int callbackPid, int callbackUid, NetworkAgentInfo nai, String callbackPackageName) {
10691 if (checkNetworkStackPermission(callbackPid, callbackUid)) {
10692 return true;
10693 }
10694
Cody Kesting160ef392021-05-05 13:17:22 -070010695 // Administrator UIDs also contains the Owner UID
10696 final int[] administratorUids = nai.networkCapabilities.getAdministratorUids();
10697 if (!CollectionUtils.contains(administratorUids, callbackUid)
10698 && !ownsVpnRunningOverNetwork(callbackUid, nai.network)) {
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010699 return false;
10700 }
10701
Cody Kesting7474f672021-05-11 14:22:40 -070010702 return !isLocationPermissionRequiredForConnectivityDiagnostics(nai)
10703 || hasLocationPermission(callbackPackageName, callbackUid);
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010704 }
10705
Cody Kestingd199a9d2019-12-17 12:55:28 -080010706 @Override
10707 public void registerConnectivityDiagnosticsCallback(
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010708 @NonNull IConnectivityDiagnosticsCallback callback,
10709 @NonNull NetworkRequest request,
10710 @NonNull String callingPackageName) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010711 Objects.requireNonNull(callback, "callback must not be null");
10712 Objects.requireNonNull(request, "request must not be null");
10713 Objects.requireNonNull(callingPackageName, "callingPackageName must not be null");
10714
Cody Kesting73708bf2019-12-18 10:57:50 -080010715 if (request.legacyType != TYPE_NONE) {
10716 throw new IllegalArgumentException("ConnectivityManager.TYPE_* are deprecated."
10717 + " Please use NetworkCapabilities instead.");
10718 }
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010719 final int callingUid = mDeps.getCallingUid();
Roshan Pius08c94fb2020-01-16 12:17:17 -080010720 mAppOpsManager.checkPackage(callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010721
10722 // This NetworkCapabilities is only used for matching to Networks. Clear out its owner uid
10723 // and administrator uids to be safe.
10724 final NetworkCapabilities nc = new NetworkCapabilities(request.networkCapabilities);
Roshan Pius08c94fb2020-01-16 12:17:17 -080010725 restrictRequestUidsForCallerAndSetRequestorInfo(nc, callingUid, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010726
10727 final NetworkRequest requestWithId =
10728 new NetworkRequest(
10729 nc, TYPE_NONE, nextNetworkRequestId(), NetworkRequest.Type.LISTEN);
10730
10731 // NetworkRequestInfos created here count towards MAX_NETWORK_REQUESTS_PER_UID limit.
10732 //
10733 // nri is not bound to the death of callback. Instead, callback.bindToDeath() is set in
10734 // handleRegisterConnectivityDiagnosticsCallback(). nri will be cleaned up as part of the
10735 // callback's binder death.
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090010736 final NetworkRequestInfo nri = new NetworkRequestInfo(callingUid, requestWithId);
Cody Kesting73708bf2019-12-18 10:57:50 -080010737 final ConnectivityDiagnosticsCallbackInfo cbInfo =
Cody Kesting83bb5fa2020-01-05 14:06:39 -080010738 new ConnectivityDiagnosticsCallbackInfo(callback, nri, callingPackageName);
Cody Kesting73708bf2019-12-18 10:57:50 -080010739
10740 mConnectivityDiagnosticsHandler.sendMessage(
10741 mConnectivityDiagnosticsHandler.obtainMessage(
10742 ConnectivityDiagnosticsHandler
10743 .EVENT_REGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
10744 cbInfo));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010745 }
10746
10747 @Override
10748 public void unregisterConnectivityDiagnosticsCallback(
10749 @NonNull IConnectivityDiagnosticsCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080010750 Objects.requireNonNull(callback, "callback must be non-null");
Cody Kesting73708bf2019-12-18 10:57:50 -080010751 mConnectivityDiagnosticsHandler.sendMessage(
10752 mConnectivityDiagnosticsHandler.obtainMessage(
10753 ConnectivityDiagnosticsHandler
10754 .EVENT_UNREGISTER_CONNECTIVITY_DIAGNOSTICS_CALLBACK,
Lorenzo Colittif61ca942020-12-15 11:02:22 +090010755 mDeps.getCallingUid(),
Cody Kesting73708bf2019-12-18 10:57:50 -080010756 0,
10757 callback));
Cody Kestingd199a9d2019-12-17 12:55:28 -080010758 }
Cody Kestingf53a0752020-04-15 12:33:28 -070010759
Yan Yanfe96dde2022-12-05 23:00:01 +000010760 private boolean hasUnderlyingTestNetworks(NetworkCapabilities nc) {
10761 final List<Network> underlyingNetworks = nc.getUnderlyingNetworks();
10762 if (underlyingNetworks == null) return false;
10763
10764 for (Network network : underlyingNetworks) {
10765 if (getNetworkCapabilitiesInternal(network).hasTransport(TRANSPORT_TEST)) {
10766 return true;
10767 }
10768 }
10769 return false;
10770 }
10771
Cody Kestingf53a0752020-04-15 12:33:28 -070010772 @Override
10773 public void simulateDataStall(int detectionMethod, long timestampMillis,
10774 @NonNull Network network, @NonNull PersistableBundle extras) {
Benedict Wong30d3ba02021-07-08 23:45:39 -070010775 Objects.requireNonNull(network, "network must not be null");
10776 Objects.requireNonNull(extras, "extras must not be null");
10777
paulhu3ffffe72021-09-16 10:15:22 +080010778 enforceAnyPermissionOf(mContext,
10779 android.Manifest.permission.MANAGE_TEST_NETWORKS,
Cody Kestingf53a0752020-04-15 12:33:28 -070010780 android.Manifest.permission.NETWORK_STACK);
10781 final NetworkCapabilities nc = getNetworkCapabilitiesInternal(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000010782 if (!nc.hasTransport(TRANSPORT_TEST) && !hasUnderlyingTestNetworks(nc)) {
10783 throw new SecurityException(
10784 "Data Stall simulation is only possible for test networks or networks built on"
10785 + " top of test networks");
Cody Kestingf53a0752020-04-15 12:33:28 -070010786 }
10787
10788 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Yan Yanfe96dde2022-12-05 23:00:01 +000010789 if (nai == null
10790 || (nai.creatorUid != mDeps.getCallingUid()
10791 && nai.creatorUid != Process.SYSTEM_UID)) {
10792 throw new SecurityException(
10793 "Data Stall simulation is only possible for network " + "creators");
Cody Kestingf53a0752020-04-15 12:33:28 -070010794 }
10795
Cody Kesting652e3ec2020-05-21 12:08:21 -070010796 // Instead of passing the data stall directly to the ConnectivityDiagnostics handler, treat
10797 // this as a Data Stall received directly from NetworkMonitor. This requires wrapping the
10798 // Data Stall information as a DataStallReportParcelable and passing to
10799 // #notifyDataStallSuspected. This ensures that unknown Data Stall detection methods are
10800 // still passed to ConnectivityDiagnostics (with new detection methods masked).
Cody Kestingb37958e2020-05-15 10:36:01 -070010801 final DataStallReportParcelable p = new DataStallReportParcelable();
10802 p.timestampMillis = timestampMillis;
10803 p.detectionMethod = detectionMethod;
10804
10805 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_DNS_EVENTS)) {
10806 p.dnsConsecutiveTimeouts = extras.getInt(KEY_DNS_CONSECUTIVE_TIMEOUTS);
10807 }
10808 if (hasDataStallDetectionMethod(p, DETECTION_METHOD_TCP_METRICS)) {
10809 p.tcpPacketFailRate = extras.getInt(KEY_TCP_PACKET_FAIL_RATE);
10810 p.tcpMetricsCollectionPeriodMillis = extras.getInt(
10811 KEY_TCP_METRICS_COLLECTION_PERIOD_MILLIS);
10812 }
10813
Serik Beketayevec8ad212020-12-07 22:43:07 -080010814 notifyDataStallSuspected(p, network.getNetId());
Cody Kestingf53a0752020-04-15 12:33:28 -070010815 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010816
lucaslin66f44212021-02-23 01:12:55 +080010817 private class NetdCallback extends BaseNetdUnsolicitedEventListener {
10818 @Override
lucaslin87b58aa2021-02-25 15:10:29 +080010819 public void onInterfaceClassActivityChanged(boolean isActive, int transportType,
lucaslin66f44212021-02-23 01:12:55 +080010820 long timestampNs, int uid) {
lucaslin87b58aa2021-02-25 15:10:29 +080010821 mNetworkActivityTracker.setAndReportNetworkActive(isActive, transportType, timestampNs);
lucaslin66f44212021-02-23 01:12:55 +080010822 }
lucaslin37a16d92021-01-21 19:48:09 +080010823
10824 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010825 public void onInterfaceLinkStateChanged(@NonNull String iface, boolean up) {
lucaslin87b58aa2021-02-25 15:10:29 +080010826 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010827 nai.clatd.interfaceLinkStateChanged(iface, up);
10828 }
10829 }
10830
10831 @Override
Chalard Jean46bfbf02022-02-02 00:56:25 +090010832 public void onInterfaceRemoved(@NonNull String iface) {
lucaslin87b58aa2021-02-25 15:10:29 +080010833 for (NetworkAgentInfo nai : mNetworkAgentInfos) {
lucaslin37a16d92021-01-21 19:48:09 +080010834 nai.clatd.interfaceRemoved(iface);
10835 }
lucaslin66f44212021-02-23 01:12:55 +080010836 }
10837 }
10838
lucaslin1a8b4c62021-01-21 02:02:55 +080010839 private final LegacyNetworkActivityTracker mNetworkActivityTracker;
10840
10841 /**
10842 * Class used for updating network activity tracking with netd and notify network activity
10843 * changes.
10844 */
10845 private static final class LegacyNetworkActivityTracker {
lucaslinb961efc2021-01-21 02:03:17 +080010846 private static final int NO_UID = -1;
lucaslin1a8b4c62021-01-21 02:02:55 +080010847 private final Context mContext;
lucaslin1193a5d2021-01-21 02:04:15 +080010848 private final INetd mNetd;
lucaslin1193a5d2021-01-21 02:04:15 +080010849 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
10850 new RemoteCallbackList<>();
10851 // Indicate the current system default network activity is active or not.
10852 @GuardedBy("mActiveIdleTimers")
10853 private boolean mNetworkActive;
10854 @GuardedBy("mActiveIdleTimers")
Chalard Jean46bfbf02022-02-02 00:56:25 +090010855 private final ArrayMap<String, IdleTimerParams> mActiveIdleTimers = new ArrayMap<>();
lucaslin1193a5d2021-01-21 02:04:15 +080010856 private final Handler mHandler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010857
Chalard Jean46bfbf02022-02-02 00:56:25 +090010858 private static class IdleTimerParams {
lucaslin1193a5d2021-01-21 02:04:15 +080010859 public final int timeout;
10860 public final int transportType;
10861
10862 IdleTimerParams(int timeout, int transport) {
10863 this.timeout = timeout;
10864 this.transportType = transport;
10865 }
10866 }
10867
10868 LegacyNetworkActivityTracker(@NonNull Context context, @NonNull Handler handler,
lucaslind5c2d072021-02-20 18:59:47 +080010869 @NonNull INetd netd) {
lucaslin1a8b4c62021-01-21 02:02:55 +080010870 mContext = context;
lucaslin1193a5d2021-01-21 02:04:15 +080010871 mNetd = netd;
10872 mHandler = handler;
lucaslin1a8b4c62021-01-21 02:02:55 +080010873 }
10874
lucaslin66f44212021-02-23 01:12:55 +080010875 public void setAndReportNetworkActive(boolean active, int transportType, long tsNanos) {
10876 sendDataActivityBroadcast(transportTypeToLegacyType(transportType), active, tsNanos);
10877 synchronized (mActiveIdleTimers) {
10878 mNetworkActive = active;
10879 // If there are no idle timers, it means that system is not monitoring
10880 // activity, so the system default network for those default network
10881 // unspecified apps is always considered active.
10882 //
10883 // TODO: If the mActiveIdleTimers is empty, netd will actually not send
10884 // any network activity change event. Whenever this event is received,
10885 // the mActiveIdleTimers should be always not empty. The legacy behavior
10886 // is no-op. Remove to refer to mNetworkActive only.
10887 if (mNetworkActive || mActiveIdleTimers.isEmpty()) {
10888 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REPORT_NETWORK_ACTIVITY));
10889 }
10890 }
10891 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010892
lucaslin1193a5d2021-01-21 02:04:15 +080010893 // The network activity should only be updated from ConnectivityService handler thread
10894 // when mActiveIdleTimers lock is held.
10895 @GuardedBy("mActiveIdleTimers")
10896 private void reportNetworkActive() {
10897 final int length = mNetworkActivityListeners.beginBroadcast();
10898 if (DDBG) log("reportNetworkActive, notify " + length + " listeners");
10899 try {
10900 for (int i = 0; i < length; i++) {
10901 try {
10902 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
10903 } catch (RemoteException | RuntimeException e) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090010904 loge("Fail to send network activity to listener " + e);
lucaslin1193a5d2021-01-21 02:04:15 +080010905 }
10906 }
10907 } finally {
10908 mNetworkActivityListeners.finishBroadcast();
10909 }
10910 }
10911
10912 @GuardedBy("mActiveIdleTimers")
10913 public void handleReportNetworkActivity() {
10914 synchronized (mActiveIdleTimers) {
10915 reportNetworkActive();
10916 }
10917 }
10918
lucaslin1a8b4c62021-01-21 02:02:55 +080010919 // This is deprecated and only to support legacy use cases.
10920 private int transportTypeToLegacyType(int type) {
10921 switch (type) {
10922 case NetworkCapabilities.TRANSPORT_CELLULAR:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010923 return TYPE_MOBILE;
lucaslin1a8b4c62021-01-21 02:02:55 +080010924 case NetworkCapabilities.TRANSPORT_WIFI:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010925 return TYPE_WIFI;
lucaslin1a8b4c62021-01-21 02:02:55 +080010926 case NetworkCapabilities.TRANSPORT_BLUETOOTH:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010927 return TYPE_BLUETOOTH;
lucaslin1a8b4c62021-01-21 02:02:55 +080010928 case NetworkCapabilities.TRANSPORT_ETHERNET:
Remi NGUYEN VAN5a42a5f2021-03-09 13:35:25 +090010929 return TYPE_ETHERNET;
lucaslin1a8b4c62021-01-21 02:02:55 +080010930 default:
10931 loge("Unexpected transport in transportTypeToLegacyType: " + type);
10932 }
10933 return ConnectivityManager.TYPE_NONE;
10934 }
10935
10936 public void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
10937 final Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
10938 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
10939 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
10940 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
10941 final long ident = Binder.clearCallingIdentity();
10942 try {
10943 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
10944 RECEIVE_DATA_ACTIVITY_CHANGE,
10945 null /* resultReceiver */,
10946 null /* scheduler */,
10947 0 /* initialCode */,
10948 null /* initialData */,
10949 null /* initialExtra */);
10950 } finally {
10951 Binder.restoreCallingIdentity(ident);
10952 }
10953 }
10954
10955 /**
10956 * Setup data activity tracking for the given network.
10957 *
10958 * Every {@code setupDataActivityTracking} should be paired with a
10959 * {@link #removeDataActivityTracking} for cleanup.
10960 */
10961 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
10962 final String iface = networkAgent.linkProperties.getInterfaceName();
10963
10964 final int timeout;
10965 final int type;
10966
10967 if (networkAgent.networkCapabilities.hasTransport(
10968 NetworkCapabilities.TRANSPORT_CELLULAR)) {
10969 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010970 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_MOBILE,
lucaslin1a8b4c62021-01-21 02:02:55 +080010971 10);
10972 type = NetworkCapabilities.TRANSPORT_CELLULAR;
10973 } else if (networkAgent.networkCapabilities.hasTransport(
10974 NetworkCapabilities.TRANSPORT_WIFI)) {
10975 timeout = Settings.Global.getInt(mContext.getContentResolver(),
paulhu56e09df2021-03-17 20:30:33 +080010976 ConnectivitySettingsManager.DATA_ACTIVITY_TIMEOUT_WIFI,
lucaslin1a8b4c62021-01-21 02:02:55 +080010977 15);
10978 type = NetworkCapabilities.TRANSPORT_WIFI;
10979 } else {
10980 return; // do not track any other networks
10981 }
10982
lucaslinb961efc2021-01-21 02:03:17 +080010983 updateRadioPowerState(true /* isActive */, type);
10984
lucaslin1a8b4c62021-01-21 02:02:55 +080010985 if (timeout > 0 && iface != null) {
10986 try {
lucaslin1193a5d2021-01-21 02:04:15 +080010987 synchronized (mActiveIdleTimers) {
10988 // Networks start up.
10989 mNetworkActive = true;
10990 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
10991 mNetd.idletimerAddInterface(iface, timeout, Integer.toString(type));
10992 reportNetworkActive();
10993 }
lucaslin1a8b4c62021-01-21 02:02:55 +080010994 } catch (Exception e) {
10995 // You shall not crash!
10996 loge("Exception in setupDataActivityTracking " + e);
10997 }
10998 }
10999 }
11000
11001 /**
11002 * Remove data activity tracking when network disconnects.
11003 */
11004 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
11005 final String iface = networkAgent.linkProperties.getInterfaceName();
11006 final NetworkCapabilities caps = networkAgent.networkCapabilities;
11007
lucaslinb961efc2021-01-21 02:03:17 +080011008 if (iface == null) return;
11009
11010 final int type;
11011 if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
11012 type = NetworkCapabilities.TRANSPORT_CELLULAR;
11013 } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
11014 type = NetworkCapabilities.TRANSPORT_WIFI;
11015 } else {
11016 return; // do not track any other networks
11017 }
11018
11019 try {
11020 updateRadioPowerState(false /* isActive */, type);
lucaslin1193a5d2021-01-21 02:04:15 +080011021 synchronized (mActiveIdleTimers) {
11022 final IdleTimerParams params = mActiveIdleTimers.remove(iface);
11023 // The call fails silently if no idle timer setup for this interface
11024 mNetd.idletimerRemoveInterface(iface, params.timeout,
11025 Integer.toString(params.transportType));
lucaslin1a8b4c62021-01-21 02:02:55 +080011026 }
lucaslinb961efc2021-01-21 02:03:17 +080011027 } catch (Exception e) {
11028 // You shall not crash!
11029 loge("Exception in removeDataActivityTracking " + e);
lucaslin1a8b4c62021-01-21 02:02:55 +080011030 }
11031 }
11032
11033 /**
11034 * Update data activity tracking when network state is updated.
11035 */
11036 public void updateDataActivityTracking(NetworkAgentInfo newNetwork,
11037 NetworkAgentInfo oldNetwork) {
11038 if (newNetwork != null) {
11039 setupDataActivityTracking(newNetwork);
11040 }
11041 if (oldNetwork != null) {
11042 removeDataActivityTracking(oldNetwork);
11043 }
11044 }
lucaslinb961efc2021-01-21 02:03:17 +080011045
11046 private void updateRadioPowerState(boolean isActive, int transportType) {
11047 final BatteryStatsManager bs = mContext.getSystemService(BatteryStatsManager.class);
11048 switch (transportType) {
11049 case NetworkCapabilities.TRANSPORT_CELLULAR:
11050 bs.reportMobileRadioPowerState(isActive, NO_UID);
11051 break;
11052 case NetworkCapabilities.TRANSPORT_WIFI:
11053 bs.reportWifiRadioPowerState(isActive, NO_UID);
11054 break;
11055 default:
11056 logw("Untracked transport type:" + transportType);
11057 }
11058 }
lucaslin1193a5d2021-01-21 02:04:15 +080011059
11060 public boolean isDefaultNetworkActive() {
11061 synchronized (mActiveIdleTimers) {
11062 // If there are no idle timers, it means that system is not monitoring activity,
11063 // so the default network is always considered active.
11064 //
11065 // TODO : Distinguish between the cases where mActiveIdleTimers is empty because
11066 // tracking is disabled (negative idle timer value configured), or no active default
11067 // network. In the latter case, this reports active but it should report inactive.
11068 return mNetworkActive || mActiveIdleTimers.isEmpty();
11069 }
11070 }
11071
11072 public void registerNetworkActivityListener(@NonNull INetworkActivityListener l) {
11073 mNetworkActivityListeners.register(l);
11074 }
11075
11076 public void unregisterNetworkActivityListener(@NonNull INetworkActivityListener l) {
11077 mNetworkActivityListeners.unregister(l);
11078 }
lucaslin012f7a12021-01-21 02:04:35 +080011079
11080 public void dump(IndentingPrintWriter pw) {
11081 synchronized (mActiveIdleTimers) {
11082 pw.print("mNetworkActive="); pw.println(mNetworkActive);
11083 pw.println("Idle timers:");
11084 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
11085 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
11086 final IdleTimerParams params = ent.getValue();
11087 pw.print(" timeout="); pw.print(params.timeout);
11088 pw.print(" type="); pw.println(params.transportType);
11089 }
11090 }
11091 }
lucaslin1a8b4c62021-01-21 02:02:55 +080011092 }
James Mattis47db0582021-01-01 14:13:35 -080011093
Daniel Brightf9e945b2020-06-15 16:10:01 -070011094 /**
11095 * Registers {@link QosSocketFilter} with {@link IQosCallback}.
11096 *
11097 * @param socketInfo the socket information
11098 * @param callback the callback to register
11099 */
11100 @Override
11101 public void registerQosSocketCallback(@NonNull final QosSocketInfo socketInfo,
11102 @NonNull final IQosCallback callback) {
11103 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(socketInfo.getNetwork());
11104 if (nai == null || nai.networkCapabilities == null) {
11105 try {
11106 callback.onError(QosCallbackException.EX_TYPE_FILTER_NETWORK_RELEASED);
11107 } catch (final RemoteException ex) {
11108 loge("registerQosCallbackInternal: RemoteException", ex);
11109 }
11110 return;
11111 }
11112 registerQosCallbackInternal(new QosSocketFilter(socketInfo), callback, nai);
11113 }
11114
11115 /**
11116 * Register a {@link IQosCallback} with base {@link QosFilter}.
11117 *
11118 * @param filter the filter to register
11119 * @param callback the callback to register
11120 * @param nai the agent information related to the filter's network
11121 */
11122 @VisibleForTesting
11123 public void registerQosCallbackInternal(@NonNull final QosFilter filter,
11124 @NonNull final IQosCallback callback, @NonNull final NetworkAgentInfo nai) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011125 Objects.requireNonNull(filter, "filter must be non-null");
11126 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011127
11128 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
Paul Hu8fc2a552022-05-04 18:44:42 +080011129 // TODO: Check allowed list here and ensure that either a) any QoS callback registered
11130 // on this network is unregistered when the app loses permission or b) no QoS
11131 // callbacks are sent for restricted networks unless the app currently has permission
11132 // to access restricted networks.
11133 enforceConnectivityRestrictedNetworksPermission(false /* checkUidsAllowedList */);
Daniel Brightf9e945b2020-06-15 16:10:01 -070011134 }
11135 mQosCallbackTracker.registerCallback(callback, filter, nai);
11136 }
11137
11138 /**
11139 * Unregisters the given callback.
11140 *
11141 * @param callback the callback to unregister
11142 */
11143 @Override
11144 public void unregisterQosCallback(@NonNull final IQosCallback callback) {
Aaron Huangc65e7fa2021-04-09 12:06:42 +080011145 Objects.requireNonNull(callback, "callback must be non-null");
Daniel Brightf9e945b2020-06-15 16:10:01 -070011146 mQosCallbackTracker.unregisterCallback(callback);
11147 }
James Mattis47db0582021-01-01 14:13:35 -080011148
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011149 private boolean isNetworkPreferenceAllowedForProfile(@NonNull UserHandle profile) {
11150 // UserManager.isManagedProfile returns true for all apps in managed user profiles.
11151 // Enterprise device can be fully managed like device owner and such use case
11152 // also should be supported. Calling app check for work profile and fully managed device
11153 // is already done in DevicePolicyManager.
11154 // This check is an extra caution to be sure device is fully managed or not.
11155 final UserManager um = mContext.getSystemService(UserManager.class);
11156 final DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
11157 if (um.isManagedProfile(profile.getIdentifier())) {
11158 return true;
11159 }
11160 if (SdkLevel.isAtLeastT() && dpm.getDeviceOwner() != null) return true;
11161 return false;
11162 }
11163
James Mattis45d81842021-01-10 14:24:24 -080011164 /**
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011165 * Set a list of default network selection policies for a user profile or device owner.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011166 *
11167 * See the documentation for the individual preferences for a description of the supported
11168 * behaviors.
11169 *
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011170 * @param profile If the device owner is set, any profile is allowed.
11171 Otherwise, the given profile can only be managed profile.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011172 * @param preferences the list of profile network preferences for the
11173 * provided profile.
Chalard Jeanfa45a682021-02-25 17:23:40 +090011174 * @param listener an optional listener to listen for completion of the operation.
11175 */
11176 @Override
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011177 public void setProfileNetworkPreferences(
11178 @NonNull final UserHandle profile,
11179 @NonNull List<ProfileNetworkPreference> preferences,
Chalard Jeanfa45a682021-02-25 17:23:40 +090011180 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011181 Objects.requireNonNull(preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011182 Objects.requireNonNull(profile);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011183
11184 if (preferences.size() == 0) {
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011185 final ProfileNetworkPreference pref = new ProfileNetworkPreference.Builder()
11186 .setPreference(ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT)
11187 .build();
11188 preferences.add(pref);
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011189 }
11190
paulhu3ffffe72021-09-16 10:15:22 +080011191 enforceNetworkStackPermission(mContext);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011192 if (DBG) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011193 log("setProfileNetworkPreferences " + profile + " to " + preferences);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011194 }
11195 if (profile.getIdentifier() < 0) {
11196 throw new IllegalArgumentException("Must explicitly specify a user handle ("
11197 + "UserHandle.CURRENT not supported)");
11198 }
Sooraj Sasindranbb65aa82022-04-20 21:16:02 -070011199 if (!isNetworkPreferenceAllowedForProfile(profile)) {
11200 throw new IllegalArgumentException("Profile must be a managed profile "
11201 + "or the device owner must be set. ");
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011202 }
paulhuaa0743d2021-05-26 21:56:03 +080011203
Chalard Jean0606fc82022-12-14 20:34:43 +090011204 final List<ProfileNetworkPreferenceInfo> preferenceList = new ArrayList<>();
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011205 boolean hasDefaultPreference = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011206 for (final ProfileNetworkPreference preference : preferences) {
11207 final NetworkCapabilities nc;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011208 boolean allowFallback = true;
Junyu Lai35665cc2022-12-19 17:37:48 +080011209 boolean blockingNonEnterprise = false;
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011210 switch (preference.getPreference()) {
11211 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_DEFAULT:
11212 nc = null;
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011213 hasDefaultPreference = true;
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011214 if (preference.getPreferenceEnterpriseId() != 0) {
11215 throw new IllegalArgumentException(
11216 "Invalid enterprise identifier in setProfileNetworkPreferences");
11217 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011218 break;
Junyu Lai35665cc2022-12-19 17:37:48 +080011219 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_BLOCKING:
11220 blockingNonEnterprise = true;
11221 // continue to process the enterprise preference.
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011222 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE_NO_FALLBACK:
11223 allowFallback = false;
11224 // continue to process the enterprise preference.
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011225 case ConnectivityManager.PROFILE_NETWORK_PREFERENCE_ENTERPRISE:
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011226 // This code is needed even though there is a check later on,
11227 // because isRangeAlreadyInPreferenceList assumes that every preference
11228 // has a UID list.
11229 if (hasDefaultPreference) {
11230 throw new IllegalArgumentException(
11231 "Default profile preference should not be set along with other "
11232 + "preference");
11233 }
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011234 if (!isEnterpriseIdentifierValid(preference.getPreferenceEnterpriseId())) {
11235 throw new IllegalArgumentException(
11236 "Invalid enterprise identifier in setProfileNetworkPreferences");
11237 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011238 final Set<UidRange> uidRangeSet =
11239 getUidListToBeAppliedForNetworkPreference(profile, preference);
11240 if (!isRangeAlreadyInPreferenceList(preferenceList, uidRangeSet)) {
11241 nc = createDefaultNetworkCapabilitiesForUidRangeSet(uidRangeSet);
11242 } else {
11243 throw new IllegalArgumentException(
11244 "Overlapping uid range in setProfileNetworkPreferences");
11245 }
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011246 nc.addCapability(NET_CAPABILITY_ENTERPRISE);
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011247 nc.addEnterpriseId(
11248 preference.getPreferenceEnterpriseId());
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011249 nc.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11250 break;
11251 default:
11252 throw new IllegalArgumentException(
11253 "Invalid preference in setProfileNetworkPreferences");
11254 }
Junyu Lai35665cc2022-12-19 17:37:48 +080011255 preferenceList.add(new ProfileNetworkPreferenceInfo(
11256 profile, nc, allowFallback, blockingNonEnterprise));
Sooraj Sasindranb0e283c2022-05-09 20:37:31 -070011257 if (hasDefaultPreference && preferenceList.size() > 1) {
11258 throw new IllegalArgumentException(
11259 "Default profile preference should not be set along with other preference");
11260 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011261 }
11262 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_PROFILE_NETWORK_PREFERENCE,
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011263 new Pair<>(preferenceList, listener)));
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011264 }
11265
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011266 private Set<UidRange> getUidListToBeAppliedForNetworkPreference(
11267 @NonNull final UserHandle profile,
11268 @NonNull final ProfileNetworkPreference profileNetworkPreference) {
11269 final UidRange profileUids = UidRange.createForUser(profile);
Sooraj Sasindran49041762022-03-09 21:59:00 -080011270 Set<UidRange> uidRangeSet = UidRangeUtils.convertArrayToUidRange(
11271 profileNetworkPreference.getIncludedUids());
11272
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011273 if (uidRangeSet.size() > 0) {
11274 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, uidRangeSet)) {
11275 throw new IllegalArgumentException(
11276 "Allow uid range is outside the uid range of profile.");
11277 }
11278 } else {
Sooraj Sasindran49041762022-03-09 21:59:00 -080011279 ArraySet<UidRange> disallowUidRangeSet = UidRangeUtils.convertArrayToUidRange(
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011280 profileNetworkPreference.getExcludedUids());
11281 if (disallowUidRangeSet.size() > 0) {
11282 if (!UidRangeUtils.isRangeSetInUidRange(profileUids, disallowUidRangeSet)) {
11283 throw new IllegalArgumentException(
11284 "disallow uid range is outside the uid range of profile.");
11285 }
11286 uidRangeSet = UidRangeUtils.removeRangeSetFromUidRange(profileUids,
11287 disallowUidRangeSet);
11288 } else {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011289 uidRangeSet = new ArraySet<>();
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011290 uidRangeSet.add(profileUids);
11291 }
11292 }
11293 return uidRangeSet;
11294 }
11295
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011296 private boolean isEnterpriseIdentifierValid(
11297 @NetworkCapabilities.EnterpriseId int identifier) {
Chalard Jean46bfbf02022-02-02 00:56:25 +090011298 if ((identifier >= NET_ENTERPRISE_ID_1) && (identifier <= NET_ENTERPRISE_ID_5)) {
Sooraj Sasindranf4a58dc2022-01-21 13:37:08 -080011299 return true;
11300 }
11301 return false;
11302 }
11303
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011304 private ArraySet<NetworkRequestInfo> createNrisFromProfileNetworkPreferences(
Chalard Jean0606fc82022-12-14 20:34:43 +090011305 @NonNull final NetworkPreferenceList<UserHandle, ProfileNetworkPreferenceInfo> prefs) {
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011306 final ArraySet<NetworkRequestInfo> result = new ArraySet<>();
Chalard Jean0606fc82022-12-14 20:34:43 +090011307 for (final ProfileNetworkPreferenceInfo pref : prefs) {
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011308 // The NRI for a user should contain the request for capabilities.
11309 // If fallback to default network is needed then NRI should include
11310 // the request for the default network. Create an image of it to
11311 // have the correct UIDs in it (also a request can only be part of one NRI, because
11312 // of lookups in 1:1 associations like mNetworkRequests).
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011313 final ArrayList<NetworkRequest> nrs = new ArrayList<>();
11314 nrs.add(createNetworkRequest(NetworkRequest.Type.REQUEST, pref.capabilities));
Sooraj Sasindran06baf4c2021-11-29 12:21:09 -080011315 if (pref.allowFallback) {
11316 nrs.add(createDefaultInternetRequestForTransport(
11317 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11318 }
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011319 if (VDBG) {
11320 loge("pref.capabilities.getUids():" + UidRange.fromIntRanges(
11321 pref.capabilities.getUids()));
11322 }
11323
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011324 setNetworkRequestUids(nrs, UidRange.fromIntRanges(pref.capabilities.getUids()));
paulhue9913722021-05-26 15:19:20 +080011325 final NetworkRequestInfo nri = new NetworkRequestInfo(Process.myUid(), nrs,
paulhu48291862021-07-14 14:53:57 +080011326 PREFERENCE_ORDER_PROFILE);
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011327 result.add(nri);
11328 }
11329 return result;
11330 }
11331
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011332 /**
11333 * Compare if the given UID range sets have the same UIDs.
11334 *
11335 */
11336 private boolean isRangeAlreadyInPreferenceList(
Chalard Jean0606fc82022-12-14 20:34:43 +090011337 @NonNull List<ProfileNetworkPreferenceInfo> preferenceList,
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011338 @NonNull Set<UidRange> uidRangeSet) {
11339 if (uidRangeSet.size() == 0 || preferenceList.size() == 0) {
11340 return false;
11341 }
Chalard Jean0606fc82022-12-14 20:34:43 +090011342 for (ProfileNetworkPreferenceInfo pref : preferenceList) {
Sooraj Sasindran499117f2021-11-29 12:40:09 -080011343 if (UidRangeUtils.doesRangeSetOverlap(
11344 UidRange.fromIntRanges(pref.capabilities.getUids()), uidRangeSet)) {
11345 return true;
11346 }
11347 }
11348 return false;
11349 }
11350
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011351 private void handleSetProfileNetworkPreference(
Chalard Jean0606fc82022-12-14 20:34:43 +090011352 @NonNull final List<ProfileNetworkPreferenceInfo> preferenceList,
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011353 @Nullable final IOnCompleteListener listener) {
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011354 /*
11355 * handleSetProfileNetworkPreference is always called for single user.
11356 * preferenceList only contains preferences for different uids within the same user
11357 * (enforced by getUidListToBeAppliedForNetworkPreference).
11358 * Clear all the existing preferences for the user before applying new preferences.
11359 *
11360 */
Chalard Jean0606fc82022-12-14 20:34:43 +090011361 mProfileNetworkPreferences = mProfileNetworkPreferences.minus(preferenceList.get(0).user);
11362 for (final ProfileNetworkPreferenceInfo preference : preferenceList) {
Sooraj Sasindrane7aee272021-11-24 20:26:55 -080011363 mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
11364 }
Sooraj Sasindran9cc129f2022-04-22 00:57:41 -070011365
paulhu74128522021-09-28 02:29:03 +000011366 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_PROFILE);
11367 addPerAppDefaultNetworkRequests(
11368 createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences));
Junyu Lai35665cc2022-12-19 17:37:48 +080011369 updateProfileAllowedNetworks();
Junyu Lai31d38bf2022-07-04 17:28:39 +080011370
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011371 // Finally, rematch.
11372 rematchAllNetworksAndRequests();
11373
11374 if (null != listener) {
11375 try {
11376 listener.onComplete();
11377 } catch (RemoteException e) {
11378 loge("Listener for setProfileNetworkPreference has died");
11379 }
11380 }
11381 }
11382
paulhu51f77dc2021-06-07 02:34:20 +000011383 @VisibleForTesting
11384 @NonNull
11385 ArraySet<NetworkRequestInfo> createNrisFromMobileDataPreferredUids(
11386 @NonNull final Set<Integer> uids) {
11387 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11388 if (uids.size() == 0) {
11389 // Should not create NetworkRequestInfo if no preferences. Without uid range in
11390 // NetworkRequestInfo, makeDefaultForApps() would treat it as a illegal NRI.
11391 if (DBG) log("Don't create NetworkRequestInfo because no preferences");
11392 return nris;
11393 }
11394
11395 final List<NetworkRequest> requests = new ArrayList<>();
11396 // The NRI should be comprised of two layers:
11397 // - The request for the mobile network preferred.
11398 // - The request for the default network, for fallback.
11399 requests.add(createDefaultInternetRequestForTransport(
Ansik605e7702021-06-29 19:06:37 +090011400 TRANSPORT_CELLULAR, NetworkRequest.Type.REQUEST));
paulhu51f77dc2021-06-07 02:34:20 +000011401 requests.add(createDefaultInternetRequestForTransport(
11402 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
11403 final Set<UidRange> ranges = new ArraySet<>();
11404 for (final int uid : uids) {
11405 ranges.add(new UidRange(uid, uid));
11406 }
11407 setNetworkRequestUids(requests, ranges);
paulhue9913722021-05-26 15:19:20 +080011408 nris.add(new NetworkRequestInfo(Process.myUid(), requests,
paulhu48291862021-07-14 14:53:57 +080011409 PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED));
paulhu51f77dc2021-06-07 02:34:20 +000011410 return nris;
11411 }
11412
11413 private void handleMobileDataPreferredUidsChanged() {
paulhu51f77dc2021-06-07 02:34:20 +000011414 mMobileDataPreferredUids = ConnectivitySettingsManager.getMobileDataPreferredUids(mContext);
paulhu74128522021-09-28 02:29:03 +000011415 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_MOBILE_DATA_PREFERERRED);
11416 addPerAppDefaultNetworkRequests(
11417 createNrisFromMobileDataPreferredUids(mMobileDataPreferredUids));
paulhu51f77dc2021-06-07 02:34:20 +000011418 // Finally, rematch.
11419 rematchAllNetworksAndRequests();
11420 }
11421
Patrick Rohr2857ac42022-01-21 14:58:16 +010011422 private void handleIngressRateLimitChanged() {
11423 final long oldIngressRateLimit = mIngressRateLimit;
11424 mIngressRateLimit = ConnectivitySettingsManager.getIngressRateLimitInBytesPerSecond(
11425 mContext);
11426 for (final NetworkAgentInfo networkAgent : mNetworkAgentInfos) {
11427 if (canNetworkBeRateLimited(networkAgent)) {
11428 // If rate limit has previously been enabled, remove the old limit first.
11429 if (oldIngressRateLimit >= 0) {
11430 mDeps.disableIngressRateLimit(networkAgent.linkProperties.getInterfaceName());
11431 }
11432 if (mIngressRateLimit >= 0) {
11433 mDeps.enableIngressRateLimit(networkAgent.linkProperties.getInterfaceName(),
11434 mIngressRateLimit);
11435 }
11436 }
11437 }
11438 }
11439
11440 private boolean canNetworkBeRateLimited(@NonNull final NetworkAgentInfo networkAgent) {
Lorenzo Colittif79dcec2022-03-07 17:48:54 +090011441 // Rate-limiting cannot run correctly before T because the BPF program is not loaded.
11442 if (!SdkLevel.isAtLeastT()) return false;
11443
Patrick Rohrff3b3f82022-02-09 15:15:52 +010011444 final NetworkCapabilities agentCaps = networkAgent.networkCapabilities;
11445 // Only test networks (they cannot hold NET_CAPABILITY_INTERNET) and networks that provide
11446 // internet connectivity can be rate limited.
11447 if (!agentCaps.hasCapability(NET_CAPABILITY_INTERNET) && !agentCaps.hasTransport(
11448 TRANSPORT_TEST)) {
Patrick Rohr2857ac42022-01-21 14:58:16 +010011449 return false;
11450 }
11451
11452 final String iface = networkAgent.linkProperties.getInterfaceName();
11453 if (iface == null) {
Patrick Rohra517f202022-02-15 11:58:41 +010011454 // This may happen in tests, but if there is no interface then there is nothing that
11455 // can be rate limited.
11456 loge("canNetworkBeRateLimited: LinkProperties#getInterfaceName returns null");
Patrick Rohr2857ac42022-01-21 14:58:16 +010011457 return false;
11458 }
11459 return true;
11460 }
11461
James Mattis45d81842021-01-10 14:24:24 -080011462 private void enforceAutomotiveDevice() {
James Mattis4ab1ffc2021-12-26 12:56:52 -080011463 PermissionUtils.enforceSystemFeature(mContext, PackageManager.FEATURE_AUTOMOTIVE,
11464 "setOemNetworkPreference() is only available on automotive devices.");
James Mattis45d81842021-01-10 14:24:24 -080011465 }
11466
11467 /**
11468 * Used by automotive devices to set the network preferences used to direct traffic at an
11469 * application level as per the given OemNetworkPreferences. An example use-case would be an
11470 * automotive OEM wanting to provide connectivity for applications critical to the usage of a
11471 * vehicle via a particular network.
11472 *
11473 * Calling this will overwrite the existing preference.
11474 *
James Mattisda32cfe2021-01-26 16:23:52 -080011475 * @param preference {@link OemNetworkPreferences} The application network preference to be set.
Chalard Jean6010c002021-03-03 16:37:13 +090011476 * @param listener {@link ConnectivityManager.OnCompleteListener} Listener used
James Mattis45d81842021-01-10 14:24:24 -080011477 * to communicate completion of setOemNetworkPreference();
James Mattis45d81842021-01-10 14:24:24 -080011478 */
James Mattis47db0582021-01-01 14:13:35 -080011479 @Override
James Mattis45d81842021-01-10 14:24:24 -080011480 public void setOemNetworkPreference(
11481 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011482 @Nullable final IOnCompleteListener listener) {
James Mattis8378aec2021-01-26 14:05:36 -080011483
James Mattisfa270db2021-05-31 17:11:10 -070011484 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11485 // Only bypass the permission/device checks if this is a valid test request.
11486 if (isValidTestOemNetworkPreference(preference)) {
11487 enforceManageTestNetworksPermission();
11488 } else {
11489 enforceAutomotiveDevice();
11490 enforceOemNetworkPreferencesPermission();
11491 validateOemNetworkPreferences(preference);
11492 }
James Mattis45d81842021-01-10 14:24:24 -080011493
James Mattis45d81842021-01-10 14:24:24 -080011494 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_OEM_NETWORK_PREFERENCE,
11495 new Pair<>(preference, listener)));
11496 }
11497
James Mattisfa270db2021-05-31 17:11:10 -070011498 /**
lucaslin3ba7cc22022-12-19 02:35:33 +000011499 * Sets the specified UIDs to get/receive the VPN as the only default network.
11500 *
11501 * Calling this will overwrite the existing network preference for this session, and the
11502 * specified UIDs won't get any default network when no VPN is connected.
11503 *
11504 * @param session The VPN session which manages the passed UIDs.
11505 * @param ranges The uid ranges which will treat VPN as the only preferred network. Clear the
11506 * setting for this session if the array is empty. Null is not allowed, the
11507 * method will use {@link Objects#requireNonNull(Object)} to check this variable.
11508 * @hide
11509 */
11510 @Override
11511 public void setVpnNetworkPreference(String session, UidRange[] ranges) {
11512 Objects.requireNonNull(ranges);
11513 enforceNetworkStackOrSettingsPermission();
11514 final UidRange[] sortedRanges = UidRangeUtils.sortRangesByStartUid(ranges);
11515 if (UidRangeUtils.sortedRangesContainOverlap(sortedRanges)) {
11516 throw new IllegalArgumentException(
11517 "setVpnNetworkPreference: Passed UID ranges overlap");
11518 }
11519
11520 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_VPN_NETWORK_PREFERENCE,
11521 new VpnNetworkPreferenceInfo(session,
11522 new ArraySet<UidRange>(Arrays.asList(ranges)))));
11523 }
11524
11525 private void handleSetVpnNetworkPreference(VpnNetworkPreferenceInfo preferenceInfo) {
11526 Log.d(TAG, "handleSetVpnNetworkPreference: preferenceInfo = " + preferenceInfo);
11527
11528 mVpnNetworkPreferences = mVpnNetworkPreferences.minus(preferenceInfo.getKey());
11529 mVpnNetworkPreferences = mVpnNetworkPreferences.plus(preferenceInfo);
11530
11531 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_VPN);
11532 addPerAppDefaultNetworkRequests(createNrisForVpnNetworkPreference(mVpnNetworkPreferences));
11533 // Finally, rematch.
11534 rematchAllNetworksAndRequests();
11535 }
11536
11537 private ArraySet<NetworkRequestInfo> createNrisForVpnNetworkPreference(
11538 @NonNull NetworkPreferenceList<String, VpnNetworkPreferenceInfo> preferenceList) {
11539 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
11540 for (VpnNetworkPreferenceInfo preferenceInfo : preferenceList) {
11541 final List<NetworkRequest> requests = new ArrayList<>();
11542 // Request VPN only, so other networks won't be the fallback options when VPN is not
11543 // connected temporarily.
11544 requests.add(createVpnRequest());
11545 final Set<UidRange> uidRanges = new ArraySet(preferenceInfo.getUidRangesNoCopy());
11546 setNetworkRequestUids(requests, uidRanges);
11547 nris.add(new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_VPN));
11548 }
11549 return nris;
11550 }
11551
11552 /**
James Mattisfa270db2021-05-31 17:11:10 -070011553 * Check the validity of an OEM network preference to be used for testing purposes.
11554 * @param preference the preference to validate
11555 * @return true if this is a valid OEM network preference test request.
11556 */
11557 private boolean isValidTestOemNetworkPreference(
11558 @NonNull final OemNetworkPreferences preference) {
11559 // Allow for clearing of an existing OemNetworkPreference used for testing.
11560 // This isn't called on the handler thread so it is possible that mOemNetworkPreferences
11561 // changes after this check is complete. This is an unlikely scenario as calling of this API
11562 // is controlled by the OEM therefore the added complexity is not worth adding given those
11563 // circumstances. That said, it is an edge case to be aware of hence this comment.
11564 final boolean isValidTestClearPref = preference.getNetworkPreferences().size() == 0
11565 && isTestOemNetworkPreference(mOemNetworkPreferences);
11566 return isTestOemNetworkPreference(preference) || isValidTestClearPref;
11567 }
11568
11569 private boolean isTestOemNetworkPreference(@NonNull final OemNetworkPreferences preference) {
11570 final Map<String, Integer> prefMap = preference.getNetworkPreferences();
11571 return prefMap.size() == 1
11572 && (prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST)
11573 || prefMap.containsValue(OEM_NETWORK_PREFERENCE_TEST_ONLY));
11574 }
11575
James Mattis45d81842021-01-10 14:24:24 -080011576 private void validateOemNetworkPreferences(@NonNull OemNetworkPreferences preference) {
11577 for (@OemNetworkPreferences.OemNetworkPreference final int pref
11578 : preference.getNetworkPreferences().values()) {
James Mattisfa270db2021-05-31 17:11:10 -070011579 if (pref <= 0 || OemNetworkPreferences.OEM_NETWORK_PREFERENCE_MAX < pref) {
11580 throw new IllegalArgumentException(
11581 OemNetworkPreferences.oemNetworkPreferenceToString(pref)
11582 + " is an invalid value.");
James Mattis45d81842021-01-10 14:24:24 -080011583 }
11584 }
11585 }
11586
11587 private void handleSetOemNetworkPreference(
11588 @NonNull final OemNetworkPreferences preference,
Chalard Jean6010c002021-03-03 16:37:13 +090011589 @Nullable final IOnCompleteListener listener) {
James Mattis45d81842021-01-10 14:24:24 -080011590 Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
11591 if (DBG) {
11592 log("set OEM network preferences :" + preference.toString());
11593 }
Chalard Jeanb5a139f2021-02-25 21:46:34 +090011594
James Mattiscb1e0362021-04-06 17:07:42 -070011595 mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
paulhu74128522021-09-28 02:29:03 +000011596 removeDefaultNetworkRequestsForPreference(PREFERENCE_ORDER_OEM);
11597 addPerAppDefaultNetworkRequests(new OemNetworkRequestFactory()
11598 .createNrisFromOemNetworkPreferences(preference));
James Mattis45d81842021-01-10 14:24:24 -080011599 mOemNetworkPreferences = preference;
James Mattis45d81842021-01-10 14:24:24 -080011600
11601 if (null != listener) {
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011602 try {
11603 listener.onComplete();
11604 } catch (RemoteException e) {
James Mattisae9aeb02021-03-01 17:09:11 -080011605 loge("Can't send onComplete in handleSetOemNetworkPreference", e);
Chalard Jean5d6e23b2021-03-01 22:00:20 +090011606 }
James Mattis45d81842021-01-10 14:24:24 -080011607 }
11608 }
11609
paulhu74128522021-09-28 02:29:03 +000011610 private void removeDefaultNetworkRequestsForPreference(final int preferenceOrder) {
paulhuaa0743d2021-05-26 21:56:03 +080011611 // Skip the requests which are set by other network preference. Because the uid range rules
11612 // should stay in netd.
11613 final Set<NetworkRequestInfo> requests = new ArraySet<>(mDefaultNetworkRequests);
paulhu48291862021-07-14 14:53:57 +080011614 requests.removeIf(request -> request.mPreferenceOrder != preferenceOrder);
paulhuaa0743d2021-05-26 21:56:03 +080011615 handleRemoveNetworkRequests(requests);
James Mattis45d81842021-01-10 14:24:24 -080011616 }
11617
James Mattis3ce3d3c2021-02-09 18:18:28 -080011618 private void addPerAppDefaultNetworkRequests(@NonNull final Set<NetworkRequestInfo> nris) {
11619 ensureRunningOnConnectivityServiceThread();
11620 mDefaultNetworkRequests.addAll(nris);
11621 final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
11622 getPerAppCallbackRequestsToUpdate();
James Mattis3ce3d3c2021-02-09 18:18:28 -080011623 final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
paulhu74128522021-09-28 02:29:03 +000011624 handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
11625 nrisToRegister.addAll(
11626 createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
11627 handleRegisterNetworkRequests(nrisToRegister);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011628 }
11629
11630 /**
11631 * All current requests that are tracking the default network need to be assessed as to whether
11632 * or not the current set of per-application default requests will be changing their default
11633 * network. If so, those requests will need to be updated so that they will send callbacks for
11634 * default network changes at the appropriate time. Additionally, those requests tracking the
11635 * default that were previously updated by this flow will need to be reassessed.
11636 * @return the nris which will need to be updated.
11637 */
11638 private ArraySet<NetworkRequestInfo> getPerAppCallbackRequestsToUpdate() {
11639 final ArraySet<NetworkRequestInfo> defaultCallbackRequests = new ArraySet<>();
11640 // Get the distinct nris to check since for multilayer requests, it is possible to have the
11641 // same nri in the map's values for each of its NetworkRequest objects.
11642 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>(mNetworkRequests.values());
James Mattis45d81842021-01-10 14:24:24 -080011643 for (final NetworkRequestInfo nri : nris) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011644 // Include this nri if it is currently being tracked.
11645 if (isPerAppTrackedNri(nri)) {
11646 defaultCallbackRequests.add(nri);
11647 continue;
11648 }
11649 // We only track callbacks for requests tracking the default.
11650 if (NetworkRequest.Type.TRACK_DEFAULT != nri.mRequests.get(0).type) {
11651 continue;
11652 }
11653 // Include this nri if it will be tracked by the new per-app default requests.
11654 final boolean isNriGoingToBeTracked =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011655 getDefaultRequestTrackingUid(nri.mAsUid) != mDefaultRequest;
James Mattis3ce3d3c2021-02-09 18:18:28 -080011656 if (isNriGoingToBeTracked) {
11657 defaultCallbackRequests.add(nri);
James Mattis45d81842021-01-10 14:24:24 -080011658 }
11659 }
James Mattis3ce3d3c2021-02-09 18:18:28 -080011660 return defaultCallbackRequests;
James Mattis45d81842021-01-10 14:24:24 -080011661 }
11662
James Mattis3ce3d3c2021-02-09 18:18:28 -080011663 /**
11664 * Create nris for those network requests that are currently tracking the default network that
11665 * are being controlled by a per-application default.
11666 * @param perAppCallbackRequestsForUpdate the baseline network requests to be used as the
11667 * foundation when creating the nri. Important items include the calling uid's original
11668 * NetworkRequest to be used when mapping callbacks as well as the caller's uid and name. These
11669 * requests are assumed to have already been validated as needing to be updated.
11670 * @return the Set of nris to use when registering network requests.
11671 */
11672 private ArraySet<NetworkRequestInfo> createPerAppCallbackRequestsToRegister(
11673 @NonNull final ArraySet<NetworkRequestInfo> perAppCallbackRequestsForUpdate) {
11674 final ArraySet<NetworkRequestInfo> callbackRequestsToRegister = new ArraySet<>();
11675 for (final NetworkRequestInfo callbackRequest : perAppCallbackRequestsForUpdate) {
11676 final NetworkRequestInfo trackingNri =
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011677 getDefaultRequestTrackingUid(callbackRequest.mAsUid);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011678
Chalard Jean9473c982021-07-29 20:03:04 +090011679 // If this nri is not being tracked, then change it back to an untracked nri.
James Mattis3ce3d3c2021-02-09 18:18:28 -080011680 if (trackingNri == mDefaultRequest) {
11681 callbackRequestsToRegister.add(new NetworkRequestInfo(
11682 callbackRequest,
11683 Collections.singletonList(callbackRequest.getNetworkRequestForCallback())));
11684 continue;
11685 }
11686
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011687 final NetworkRequest request = callbackRequest.mRequests.get(0);
James Mattis3ce3d3c2021-02-09 18:18:28 -080011688 callbackRequestsToRegister.add(new NetworkRequestInfo(
11689 callbackRequest,
11690 copyNetworkRequestsForUid(
Lorenzo Colitti3e367f42021-03-12 22:50:57 +090011691 trackingNri.mRequests, callbackRequest.mAsUid,
Lorenzo Colitti2a49c5d2021-03-12 22:48:07 +090011692 callbackRequest.mUid, request.getRequestorPackageName())));
James Mattis3ce3d3c2021-02-09 18:18:28 -080011693 }
11694 return callbackRequestsToRegister;
James Mattis45d81842021-01-10 14:24:24 -080011695 }
11696
Chalard Jean17215832021-03-01 14:06:28 +090011697 private static void setNetworkRequestUids(@NonNull final List<NetworkRequest> requests,
11698 @NonNull final Set<UidRange> uids) {
Chalard Jean17215832021-03-01 14:06:28 +090011699 for (final NetworkRequest req : requests) {
Chiachang Wang8156c4e2021-03-19 00:45:39 +000011700 req.networkCapabilities.setUids(UidRange.toIntRanges(uids));
Chalard Jean17215832021-03-01 14:06:28 +090011701 }
11702 }
11703
James Mattis45d81842021-01-10 14:24:24 -080011704 /**
11705 * Class used to generate {@link NetworkRequestInfo} based off of {@link OemNetworkPreferences}.
11706 */
11707 @VisibleForTesting
11708 final class OemNetworkRequestFactory {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011709 ArraySet<NetworkRequestInfo> createNrisFromOemNetworkPreferences(
James Mattis45d81842021-01-10 14:24:24 -080011710 @NonNull final OemNetworkPreferences preference) {
James Mattis3ce3d3c2021-02-09 18:18:28 -080011711 final ArraySet<NetworkRequestInfo> nris = new ArraySet<>();
James Mattis45d81842021-01-10 14:24:24 -080011712 final SparseArray<Set<Integer>> uids =
11713 createUidsFromOemNetworkPreferences(preference);
11714 for (int i = 0; i < uids.size(); i++) {
11715 final int key = uids.keyAt(i);
11716 final Set<Integer> value = uids.valueAt(i);
11717 final NetworkRequestInfo nri = createNriFromOemNetworkPreferences(key, value);
11718 // No need to add an nri without any requests.
11719 if (0 == nri.mRequests.size()) {
11720 continue;
11721 }
11722 nris.add(nri);
11723 }
11724
11725 return nris;
11726 }
11727
11728 private SparseArray<Set<Integer>> createUidsFromOemNetworkPreferences(
11729 @NonNull final OemNetworkPreferences preference) {
James Mattisb6b6a432021-06-01 22:30:36 -070011730 final SparseArray<Set<Integer>> prefToUids = new SparseArray<>();
James Mattis45d81842021-01-10 14:24:24 -080011731 final PackageManager pm = mContext.getPackageManager();
James Mattisae9aeb02021-03-01 17:09:11 -080011732 final List<UserHandle> users =
11733 mContext.getSystemService(UserManager.class).getUserHandles(true);
11734 if (null == users || users.size() == 0) {
11735 if (VDBG || DDBG) {
11736 log("No users currently available for setting the OEM network preference.");
11737 }
James Mattisb6b6a432021-06-01 22:30:36 -070011738 return prefToUids;
James Mattisae9aeb02021-03-01 17:09:11 -080011739 }
James Mattis45d81842021-01-10 14:24:24 -080011740 for (final Map.Entry<String, Integer> entry :
11741 preference.getNetworkPreferences().entrySet()) {
11742 @OemNetworkPreferences.OemNetworkPreference final int pref = entry.getValue();
James Mattisb6b6a432021-06-01 22:30:36 -070011743 // Add the rules for all users as this policy is device wide.
11744 for (final UserHandle user : users) {
11745 try {
11746 final int uid = pm.getApplicationInfoAsUser(entry.getKey(), 0, user).uid;
11747 if (!prefToUids.contains(pref)) {
11748 prefToUids.put(pref, new ArraySet<>());
11749 }
11750 prefToUids.get(pref).add(uid);
11751 } catch (PackageManager.NameNotFoundException e) {
11752 // Although this may seem like an error scenario, it is ok that uninstalled
11753 // packages are sent on a network preference as the system will watch for
11754 // package installations associated with this network preference and update
11755 // accordingly. This is done to minimize race conditions on app install.
11756 continue;
James Mattis45d81842021-01-10 14:24:24 -080011757 }
James Mattis45d81842021-01-10 14:24:24 -080011758 }
11759 }
James Mattisb6b6a432021-06-01 22:30:36 -070011760 return prefToUids;
James Mattis45d81842021-01-10 14:24:24 -080011761 }
11762
11763 private NetworkRequestInfo createNriFromOemNetworkPreferences(
11764 @OemNetworkPreferences.OemNetworkPreference final int preference,
11765 @NonNull final Set<Integer> uids) {
11766 final List<NetworkRequest> requests = new ArrayList<>();
11767 // Requests will ultimately be evaluated by order of insertion therefore it matters.
11768 switch (preference) {
11769 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID:
11770 requests.add(createUnmeteredNetworkRequest());
11771 requests.add(createOemPaidNetworkRequest());
James Mattisa117e282021-04-20 17:26:30 -070011772 requests.add(createDefaultInternetRequestForTransport(
11773 TYPE_NONE, NetworkRequest.Type.TRACK_DEFAULT));
James Mattis45d81842021-01-10 14:24:24 -080011774 break;
11775 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_NO_FALLBACK:
11776 requests.add(createUnmeteredNetworkRequest());
11777 requests.add(createOemPaidNetworkRequest());
11778 break;
11779 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PAID_ONLY:
11780 requests.add(createOemPaidNetworkRequest());
11781 break;
11782 case OemNetworkPreferences.OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY:
11783 requests.add(createOemPrivateNetworkRequest());
11784 break;
James Mattisfa270db2021-05-31 17:11:10 -070011785 case OEM_NETWORK_PREFERENCE_TEST:
11786 requests.add(createUnmeteredNetworkRequest());
11787 requests.add(createTestNetworkRequest());
11788 requests.add(createDefaultRequest());
11789 break;
11790 case OEM_NETWORK_PREFERENCE_TEST_ONLY:
11791 requests.add(createTestNetworkRequest());
11792 break;
James Mattis45d81842021-01-10 14:24:24 -080011793 default:
11794 // This should never happen.
11795 throw new IllegalArgumentException("createNriFromOemNetworkPreferences()"
11796 + " called with invalid preference of " + preference);
11797 }
11798
James Mattisfa270db2021-05-31 17:11:10 -070011799 final ArraySet<UidRange> ranges = new ArraySet<>();
Chalard Jean17215832021-03-01 14:06:28 +090011800 for (final int uid : uids) {
11801 ranges.add(new UidRange(uid, uid));
11802 }
11803 setNetworkRequestUids(requests, ranges);
paulhu48291862021-07-14 14:53:57 +080011804 return new NetworkRequestInfo(Process.myUid(), requests, PREFERENCE_ORDER_OEM);
James Mattis45d81842021-01-10 14:24:24 -080011805 }
11806
11807 private NetworkRequest createUnmeteredNetworkRequest() {
11808 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11809 .addCapability(NET_CAPABILITY_NOT_METERED)
11810 .addCapability(NET_CAPABILITY_VALIDATED);
11811 return createNetworkRequest(NetworkRequest.Type.LISTEN, netcap);
11812 }
11813
11814 private NetworkRequest createOemPaidNetworkRequest() {
11815 // NET_CAPABILITY_OEM_PAID is a restricted capability.
11816 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11817 .addCapability(NET_CAPABILITY_OEM_PAID)
11818 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11819 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11820 }
11821
11822 private NetworkRequest createOemPrivateNetworkRequest() {
11823 // NET_CAPABILITY_OEM_PRIVATE is a restricted capability.
11824 final NetworkCapabilities netcap = createDefaultPerAppNetCap()
11825 .addCapability(NET_CAPABILITY_OEM_PRIVATE)
11826 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
11827 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
11828 }
11829
11830 private NetworkCapabilities createDefaultPerAppNetCap() {
James Mattisfa270db2021-05-31 17:11:10 -070011831 final NetworkCapabilities netcap = new NetworkCapabilities();
11832 netcap.addCapability(NET_CAPABILITY_INTERNET);
11833 netcap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
11834 return netcap;
11835 }
11836
11837 private NetworkRequest createTestNetworkRequest() {
11838 final NetworkCapabilities netcap = new NetworkCapabilities();
11839 netcap.clearAll();
11840 netcap.addTransportType(TRANSPORT_TEST);
11841 return createNetworkRequest(NetworkRequest.Type.REQUEST, netcap);
James Mattis45d81842021-01-10 14:24:24 -080011842 }
James Mattis47db0582021-01-01 14:13:35 -080011843 }
markchien738ad912021-12-09 18:15:45 +080011844
11845 @Override
11846 public void updateMeteredNetworkAllowList(final int uid, final boolean add) {
11847 enforceNetworkStackOrSettingsPermission();
11848
11849 try {
11850 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011851 mBpfNetMaps.addNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011852 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011853 mBpfNetMaps.removeNiceApp(uid);
markchien738ad912021-12-09 18:15:45 +080011854 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011855 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011856 throw new IllegalStateException(e);
11857 }
11858 }
11859
11860 @Override
11861 public void updateMeteredNetworkDenyList(final int uid, final boolean add) {
11862 enforceNetworkStackOrSettingsPermission();
11863
11864 try {
11865 if (add) {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011866 mBpfNetMaps.addNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011867 } else {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011868 mBpfNetMaps.removeNaughtyApp(uid);
markchien738ad912021-12-09 18:15:45 +080011869 }
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011870 } catch (ServiceSpecificException e) {
markchien738ad912021-12-09 18:15:45 +080011871 throw new IllegalStateException(e);
11872 }
11873 }
markchiene1561fa2021-12-09 22:00:56 +080011874
11875 @Override
markchien3c04e662022-03-22 16:29:56 +080011876 public void setUidFirewallRule(final int chain, final int uid, final int rule) {
markchiene1561fa2021-12-09 22:00:56 +080011877 enforceNetworkStackOrSettingsPermission();
11878
markchien3c04e662022-03-22 16:29:56 +080011879 // There are only two type of firewall rule: FIREWALL_RULE_ALLOW or FIREWALL_RULE_DENY
11880 int firewallRule = getFirewallRuleType(chain, rule);
11881
11882 if (firewallRule != FIREWALL_RULE_ALLOW && firewallRule != FIREWALL_RULE_DENY) {
11883 throw new IllegalArgumentException("setUidFirewallRule with invalid rule: " + rule);
11884 }
11885
markchiene1561fa2021-12-09 22:00:56 +080011886 try {
markchien3c04e662022-03-22 16:29:56 +080011887 mBpfNetMaps.setUidRule(chain, uid, firewallRule);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011888 } catch (ServiceSpecificException e) {
markchiene1561fa2021-12-09 22:00:56 +080011889 throw new IllegalStateException(e);
11890 }
11891 }
markchien98a6f952022-01-13 23:43:53 +080011892
Motomu Utsumi900b8062023-01-19 16:16:49 +090011893 @Override
11894 public int getUidFirewallRule(final int chain, final int uid) {
11895 enforceNetworkStackOrSettingsPermission();
11896 return mBpfNetMaps.getUidRule(chain, uid);
11897 }
11898
markchien3c04e662022-03-22 16:29:56 +080011899 private int getFirewallRuleType(int chain, int rule) {
11900 final int defaultRule;
11901 switch (chain) {
11902 case ConnectivityManager.FIREWALL_CHAIN_STANDBY:
Motomu Utsumid9801492022-06-01 13:57:27 +000011903 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1:
11904 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2:
Motomu Utsumi1d9054b2022-06-06 07:44:05 +000011905 case ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3:
markchien3c04e662022-03-22 16:29:56 +080011906 defaultRule = FIREWALL_RULE_ALLOW;
11907 break;
11908 case ConnectivityManager.FIREWALL_CHAIN_DOZABLE:
11909 case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
11910 case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
11911 case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
11912 defaultRule = FIREWALL_RULE_DENY;
11913 break;
11914 default:
11915 throw new IllegalArgumentException("Unsupported firewall chain: " + chain);
11916 }
11917 if (rule == FIREWALL_RULE_DEFAULT) rule = defaultRule;
11918
11919 return rule;
11920 }
11921
markchien98a6f952022-01-13 23:43:53 +080011922 @Override
11923 public void setFirewallChainEnabled(final int chain, final boolean enable) {
11924 enforceNetworkStackOrSettingsPermission();
11925
11926 try {
Wayne Ma2fde98c2022-01-17 18:04:05 +080011927 mBpfNetMaps.setChildChain(chain, enable);
Lorenzo Colitti82244fd2022-03-04 23:15:00 +090011928 } catch (ServiceSpecificException e) {
markchien98a6f952022-01-13 23:43:53 +080011929 throw new IllegalStateException(e);
11930 }
11931 }
11932
markchien00a0bed2022-01-13 23:46:13 +080011933 @Override
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011934 public boolean getFirewallChainEnabled(final int chain) {
11935 enforceNetworkStackOrSettingsPermission();
11936
Motomu Utsumi25cf86f2022-06-27 08:50:19 +000011937 return mBpfNetMaps.isChainEnabled(chain);
Motomu Utsumibe3ff1e2022-06-08 10:05:07 +000011938 }
11939
11940 @Override
markchien00a0bed2022-01-13 23:46:13 +080011941 public void replaceFirewallChain(final int chain, final int[] uids) {
11942 enforceNetworkStackOrSettingsPermission();
11943
Motomu Utsumi9be2ea02022-07-05 06:14:59 +000011944 mBpfNetMaps.replaceUidChain(chain, uids);
markchien00a0bed2022-01-13 23:46:13 +080011945 }
Igor Chernyshev9dac6602022-12-13 19:28:32 -080011946
11947 @Override
11948 public IBinder getCompanionDeviceManagerProxyService() {
11949 enforceNetworkStackPermission(mContext);
11950 return mCdmps;
11951 }
Nathan Haroldb89cbfb2018-07-30 13:38:01 -070011952}